自定义接口错误响应格式

基础小知识
laravel 处理异常的位置在 app/Exceptions 这个目录,如果新建异常类,就在这个目录
这个目录中,最重要的是 Handler.php 这个文件,如何处理渲染异常,是这个类的 rander 方法。如果你需要自定义错误输出,其实就是重写这个 rander 方法。

1.在 app/Exceptions 下新建 ApiException

 1 <?php
 2 namespace AppExceptions;
 3 
 4 use Exception;
 5 
 6 class ApiException extends Exception
 7 {
 8     const HTTP_OK = 200;
 9 
10     protected $data;
11 
12     protected $code;
13 
14     public function __construct($data, $code = self::HTTP_OK, array $meta = [])
15     {
16         // 第一个参数是data,是因为想兼容string和array两种数据结构
17         // 第二个参数默认取200,是因为公司前端框架限制,所以是status取200,错误码用code表示
18         // 如果第二个参数是任意httpStatus(如200,201,204,301,422,500),就只返回httpStatus,如果是自定义错误编码,(如600101,600102),就返回httpstatus为200,返回体中包含message和code。
19         // 第三个参数默认为空数组,如果在message和code之外,还需要返回数组,就传递第三个参数
20         $this->data = $data;
21         $this->code = $code;
22         $this->meta = $meta;
23 //        parent::__construct($data, $code);
24     }
25 
26     public function render()
27     {
28         $httpStatus = getHttpStatus();
29         $status  = in_array($this->code, $httpStatus) ? $this->code : self::HTTP_OK;
30         $content = [];
31         if (is_array($this->data)) {
32             $content = $this->data;
33         }
34         if (is_string($this->data)) {
35             $content = in_array($this->code, $httpStatus)
36                 ? [
37                     'message' => $this->data
38                 ]
39                 : [
40                     'message' => $this->data,
41                     'code'    => $this->code,
42                     //                    'timestamp' => time()
43                 ];
44         }
45 
46         if ($this->meta) {
47             $content = array_add($content, 'meta', $this->meta);
48         }
49 
50         return response($content, $status);
51     }
52 }

2.在vendorlaravelframeworksrcIlluminateFoundation helpers.php 中增加函数:(或者直接写在这个异常类中,私有调用

该函数是获取 Symfony 定义的所有 Http 状态码。比如 200=HTTP_OK。

 1 /*
 2  * 获取 Symfony 定义的所有 Http 状态码
 3  * @auth jackie <2019.08.06>
 4  */
 5 function getHttpStatus()
 6 {
 7     $objClass = new ReflectionClass(SymfonyComponentHttpFoundationResponse::class);
 8     // 此处获取类中定义的全部常量 返回的是 [key=>value,...] 的数组,key是常量名,value是常量值
 9     return array_values($objClass->getConstants());
10 }

3.使用

ApiException($data, int $code=200, array $meta=[]);
第 1 个参数可以为 string 或 array.
第 2 个参数默认为 200,如果传的 code 是任意一个 httpStatus,表示返回的 http 状态码(如 404、500 等),
如果是自定义错误码(非任意一个 httpStatus,如 1001、1002),则 http 状态码返回 200,code 码在 json 内容中返回
第 3 个参数默认为空数组。如果传第 3 个参数,将一起返回。

1 use AppExceptionsApiException;
2 
3 
4 throw new ApiException(['msg' => '都是好孩子', 'code' => '123'], 403);

 

3.1 参数传 string

throw new BaseException('都是好孩子');

Status: 200 OK 
{
    "message": "都是好孩子"
}

3.2 参数传 string,code (自定义错误码,非 httpStatus)

throw new BaseException('都是好孩子',1001);

Status: 200 OK 
{
    "message": "都是好孩子",
    "code": 1001
}

3.3 参数传 string,code(httpStatus)

throw new BaseException('都是好孩子', 404);

Status: 404 Not Found
{
    "message": "都是好孩子"
}

3.4 参数传 array

throw new BaseException(['msg' => '都是好孩子', 'code' => '123']);

Status: 200 OK
{
    "msg": "都是好孩子",
    "code": "123"
}

3.5 参数传 array,code(httpStatus)

throw new BaseException(['msg' => '都是好孩子', 'code' => '123'], 403);

Status: 403 Forbidden
{
    "msg": "都是好孩子",
    "code": "123"
}

3.6 参数传 string,code(httpStatus),array

throw new BaseException('都是好孩子', 422, ['msg' => '天是蓝的', 'code' => '24678']);

Status: 422 Unprocessable Entity
{
    "message": "都是好孩子",
    "meta": {
        "msg": "天是蓝的",
        "code": "24678"
    }
}

3.7 参数传 string,code(自定义错误码,非 httpStatus),array

throw new BaseException('都是好孩子', 4567, ['msg' => '天是蓝的', 'code' => '24678']);

Status: 200 OK
{
    "message": "都是好孩子",
    "code": 4567,
    "meta": {
        "msg": "天是蓝的",
        "code": “24678"  
    }
}

3.8 参数传 array,code(自定义错误码,非 httpStatus),array

throw new BaseException(['msg' => '都是好孩子', 'code' => '123'], 1234, ['msg' => '天是蓝的', 'code' => '24678']);

Status: 200 OK
{
    "msg": "都是好孩子",
    "code": "123",
    "meta": {
        "msg": "天是蓝的",
        "code": "24678"
    }
}

3.9 参数传 array,code(自定义错误码,非 httpStatus),array

throw new BaseException(['msg' => '都是好孩子', 'code' => '123'], 500, ['msg' => '天是蓝的', 'code' => '24678']);

Status: 500 Internal Server Error
{
    "msg": "都是好孩子",
    "code": "123",
    "meta": {
        "msg": "天是蓝的",
        "code": "24678"
    }
}

更多使用:https://learnku.com/articles/24911

原文地址:https://www.cnblogs.com/clubs/p/11310201.html