laravel接管Dingo-api和默认的错误处理方式

吾爱主题 阅读:143 2021-09-15 15:52:00 评论:0

接管Dingo-api的错误

如上图所示,AppServiceProvider.php中的register()方法中添加如下代码

  1. \API::error(function (\Illuminate\Validation\ValidationException $exception){
  2. $data =$exception->validator->getMessageBag();
  3. $msg = collect($data)->first();
  4. if(is_array($msg)){
  5. $msg = $msg[0];
  6. }
  7. return response()->json(['message'=>$msg,'status_code'=>400], 200);
  8. });
  9. \API::error(function (\Dingo\Api\Exception\ValidationHttpException $exception){
  10. $errors = $exception->getErrors();
  11. return response()->json(['message'=>$errors->first(),'status_code'=>400], 200);
  12. });

接管laravel的错误

在Exceptions的Handler.php的render中写入以下代码

  1. public function render($request, Exception $exception)
  2. {
  3. if($exception instanceof \Illuminate\Validation\ValidationException){
  4. $data = $exception->validator->getMessageBag();
  5. $msg = collect($data)->first();
  6. if(is_array($msg)){
  7. $msg = $msg[0];
  8. }
  9. return response()->json(['message'=>$msg],200);
  10. }
  11.  
  12. if (in_array('api',$exception->guards())){
  13. if($exception instanceof AuthenticationException){
  14. return response()->json(['message'=>'token错误'],200);
  15. }
  16. if($exception instanceof ModelNotFoundException){
  17. return response()->json(['message'=>'该模型未找到'],200);
  18. }
  19.  
  20. }
  21.  
  22. return parent::render($request, $exception);
  23. }

以上这篇laravel接管Dingo-api和默认的错误处理方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

原文链接:https://blog.csdn.net/zhangatle/article/details/80945041

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容