Laravel+Dingo/Api 自定义响应

栏目: PHP · 发布时间: 5年前

内容简介:在最近的开发开发项目中,我使用了刚开始使用

在最近的开发开发项目中,我使用了 Dingo/Api 这个第三方 Api 库。

Dingo 是个很强大的 Api 库, 但在开发的过程中,需要自定义响应字段。

刚开始使用 Ding/Api 时,返回如下:

{
    "message": "422 Unprocessable Entity",
    "errors": {
        "mobile": [
            "手机号格式不正确"
        ]
    },
    "status_code": 422
}

这是输入字段验证错误时, Dingo 返回的结果。

这样看上去没什么问题。因为这边 status_code 是比较规范的。对于 PHP 来说,直接 json_decode 之后,并没有什么难办的地方。但是对面安卓和 IOS 则是使用的强类型语言。尤其是 Java,需要对每一个 Json 对象进行新建,然后序列化。所以,这种格式不统一的返回结果,是无法接受的

解决方法: 我们需要将所有的异常信息归总到一个地方,在 AppServiceProviderboot() 方法中添加

// 将所有的 Exception 全部交给 App\Exceptions\Handler 来处理
app('api.exception')->register(function (Exception $exception) {
    $request = Illuminate\Http\Request::capture();
    return app('App\Exceptions\Handler')->render($request, $exception);
});

然后在 App\Exceptions\Handler.php 中的 render() 方法中:

$class = get_class($exception);
switch ($class) {
    case 'Dingo\Api\Exception\ValidationHttpException':
        if ($request->expectsJson())
            return $this->errorRespond($exception->getErrors()->first(), $exception->getStatusCode());
        break;

    default:
        if ($request->expectsJson())
            return $this->errorRespond('系统休息了', 500000);

        break;
}

再次访问接口:

{
    "response_status_code": 422,
    "response_message": "请填写手机号",
    "data": []
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Boolean Reasoning

Boolean Reasoning

Brown, Frank Markham / 2003-4 / $ 19.15

A systematic treatment of Boolean reasoning, this concise, newly revised edition combines the works of early logicians with recent investigations, including previously unpublished research results. Th......一起来看看 《Boolean Reasoning》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

在线进制转换器
在线进制转换器

各进制数互转换器