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

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

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

方法:

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

 
  1. app('api.exception')->register(function (\Exception $exception) {

  2. $request = Request::capture();

  3. return app('App\Exceptions\Handler')->render($request, $exception);

  4. });

然后在 app\Exceptions\Handler.php 中 重写 laravel核心包的方法convertValidationExceptionToResponse(),具体代码如下:

 
  1. public function convertValidationExceptionToResponse(ValidationException $e, $request)

  2. {

  3. $data = $e->validator->getMessageBag();

  4. $msg = collect($data)->first();

  5. if(is_array($msg)){

  6. $msg = $msg[0];

  7. }

  8. return ['code'=> -1,'msg'=>$msg];

  9. }

这个方法里面的代码仅供参考,可自由发挥。

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

猜你喜欢

转载自blog.csdn.net/sunjinyan_1/article/details/81136874