Laravel+Dingo/Api 自定义响应
在最近的开发开发项目中,我使用了Dingo/Api这个第三方Api库。Dingo是个很强大的Api库, 但在开发的过程中,需要自定义响应字段。
刚开始使用Ding/Api时,返回如下:
{
"message": "422 Unprocessable Entity",
"errors": {
"mobile": [
"手机号格式不正确"
]
},
"status_code": 422
}这是输入字段验证错误时,Dingo返回的结果。
解决方法: 我们需要将所有的异常信息归总到一个地方,在AppServiceProvider的boot()方法中添加
// 将所有的 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": []
} 相关推荐
染血白衣 2020-11-16
SAMXIE 2020-11-04
一个智障 2020-11-15
学习web前端 2020-11-09
yiranpiaoluo 2020-11-04
lxhuang 2020-11-03
82387067 2020-11-03
huangliuyu00 2020-10-29
Dayer 2020-10-27
小马的学习笔记 2020-10-23
liuweiITlove 2020-10-14
kjyiyi 2020-10-10
fanjunjaden 2020-10-09
zhyue 2020-09-28
huangliuyu00 2020-09-24
88397813 2020-09-23
jyj0 2020-09-21