在最近的开发开发项目中,我使用了Dingo/Api
这个第三方Api
库。Dingo
是个很强大的Api
库, 但在开发的过程当中,须要自定义响应字段。php
刚开始使用Ding/Api
时,返回以下:json
{ "message": "422 Unprocessable Entity", "errors": { "mobile": [ "手机号格式不正确" ] }, "status_code": 422 }
这是输入字段验证错误时,Dingo
返回的结果。api
这样看上去没什么问题。由于这边 status_code 是比较规范的。对于 PHP 来讲,直接 json_decode 以后,并无什么难办的地方。可是对面安卓和 IOS 则是使用的强类型语言。尤为是 Java,须要对每个 Json 对象进行新建,而后序列化。因此,这种格式不统一的返回结果,是没法接受的
解决方法: 咱们须要将全部的异常信息归总到一个地方,在AppServiceProvider
的boot()
方法中添加app
// 将全部的 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()
方法中:ide
$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; }
再次访问接口:this
{ "response_status_code": 422, "response_message": "请填写手机号", "data": [] }