Laravel集成Dingo/Api背景与痛点
在最近的项目开发中,笔者引入了Dingo/Api这一第三方API库进行接口构建。
尽管Dingo功能强大,但在实际业务逻辑中,往往需要对返回的响应字段进行定制化调整。
初次接入Dingo/Api时,系统默认的返回数据结构如下所示:
{
"message": "422 Unprocessable Entity",
"errors": {
"mobile": [
"手机号格式不正确"
]
},
"status_code": 422
}
上述输出即为输入字段验证失败时,Dingo框架自动生成的响应结果。
从PHP后端视角来看,该结构并无明显缺陷,因为直接调用json_decode解析即可获取数据。然而,面对Android和iOS等采用强类型语言的客户端,尤其是Java环境,开发者需针对每个JSON对象实例化并执行序列化操作。因此,这种嵌套且格式不统一的返回结构难以被前端高效接受。
为解决此问题,需将所有异常信息集中处理。具体做法是在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": []
}
以上即为基于Laravel与Dingo/Api实现自定义统一响应格式的完整流程,希望能为相关开发者提供有益参考。