首页 > 编程 > Python > 正文

Laravel+Dingo/Api 自定义响应的实现

2019-11-25 13:16:40
字体:
来源:转载
供稿:网友

在最近的开发开发项目中,我使用了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 对象进行新建,然后序列化。所以,这种格式不统一的返回结果,是无法接受的

解决方法: 我们需要将所有的异常信息归总到一个地方,在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": []}

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表