laravel dingo API返回自定义错误信息

来源:互联网 发布:淘宝商品被删除 恢复 编辑:程序博客网 时间:2024/05/26 12:07

 laravel 在使用了 dingo API 后,错误信息被dingo异常类接管了,返回信息变成了 :

      要返回自定义的错误信息,就需要再把错误异常类接管回来(大概这个意思...)

方法:

在  app\Providers\AppServiceProvider.php  中的 boot() 方法 添加如下代码:

 app('api.exception')->register(function (\Exception $exception) {     $request = Request::capture();     return app('App\Exceptions\Handler')->render($request, $exception); });
然后在 app\Exceptions\Handler.php 中 重写 laravel核心包的方法convertValidationExceptionToResponse(),具体代码如下:

public function convertValidationExceptionToResponse(ValidationException $e, $request){    $data = $e->validator->getMessageBag();    $msg = collect($data)->first();    if(is_array($msg)){        $msg = $msg[0];    }    return ['code'=> -1,'msg'=>$msg];}
这个方法里面的代码仅供参考,可自由发挥。

  之后再调用接口会发现:,内容为自定义的了。

阅读全文
0 0
原创粉丝点击