Laravel框架统一异常捕获并返回自定义错误信息

56次阅读
没有评论

原文链接:https://blog.csdn.net/ltbweber/article/details/139631298

Laravel 框架中,App\Exceptions\Hander.php 为异常捕获的统一处理地方,可以在这里自定义你想处理的任何错误信息,并友好的返回自定义错误信息。主要涉及到 2 个方法,report 和 render。如下图所示,render 方法里为自定义捕获的错误类型,返回数据以及状态码可根据自己爱好自定义,下面为常见的一些错误类型捕获:

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Database\QueryException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class Handler extends ExceptionHandler
{
    /**
    * The list of the inputs that are never flashed to the session on validation exceptions.
    *
    * @var array<int, string>
    */
    protected $dontFlash = [
       'current_password',
       'password',
       'password_confirmation',
    ];

    /**
    * Register the exception handling callbacks for the application.
    */
    public function register(): void
    {$this->reportable(function (Throwable $e) {// 比如可以进行记录错误信息到数据表,或打印错误日志等操作});
    }

    public function report(Throwable $exception)
    {parent::report($exception);
    }

    public function render($request, Throwable $exception)
    {

        $code = 0;
        $msg = '';
        if ($exception instanceof HttpException) {

            $code = 500;
            $msg = 'http 请求错误,请稍后重试';
        }else if ($exception instanceof NotFoundHttpException) {

            $code = 404;
            $msg = '访问的地址不存在';
        }else if ($exception instanceof MethodNotAllowedHttpException) {

            $code = 405;
            $msg = 'http 请求方式不被允许,请检查后重试';
        }else if ($exception instanceof QueryException) {

            $code = 500;
            $msg = '数据处理错误,请稍后重试';
        }else if ($exception instanceof ModelNotFoundException) {

            $code = 404;
            $msg = '模型未找到,请稍后重试';

        } else if ($exception instanceof \ReflectionException) {

            $code = 500;
            $msg = '项目反射类 / 方法 / 函数错误,请稍后重试';
        }else if ($exception instanceof \ErrorException) {

            $code = 500;
            $msg = '发生 error 错误,请稍后重试';
        }else if ($exception instanceof \Runtimeexception){

            $code = 500;
            $msg = '程序运行出错,请稍后重试';
        }

        if ($code > 0) {Log::info('错误:',['code'=>$code,'msg'=>$msg,'data'=>$exception->getMessage()]);
            return response()->json(['code'=>$code,'message'=>$msg], $code);
        }
        return parent::render($request, $exception);

    }

}
正文完
有偿技术支持加微信
post-qrcode
 0
评论(没有评论)
验证码