laravel9 错误处理

Laravel框架
475
0
0
2022-10-05
标签   Laravel基础

旧版异常

Handler

class Handler extends ExceptionHandler
{

  public function render($request, Exception $exception)
  {
      //ajax请求我们才捕捉异常 
      if ($request->ajax()){
          // 将方法拦截到自己的ExceptionReport 
          $reporter = ExceptionReport::make($exception);
          if ($reporter->shouldReturn()){
              return $reporter->report();
          }
          if(env('APP_DEBUG')){
              //开发环境,则显示详细错误信息 
              return parent::render($request, $exception);
          }else{
              //线上环境,未知错误,则显示500 
              return $reporter->prodReport();
          }
      }
      return parent::render($request, $exception);
  }
}

laravel9 异常

ExceptionReport

class ExceptionReport
{
    public static $doReportOther = [
        AuthenticationException::class => ['未授权',401],
        ModelNotFoundException::class => ['该模型未找到',404],
        AuthorizationException::class => ['没有此权限',403],
        ValidationException::class => [],
        UnauthorizedHttpException::class=>['未登录或登录状态失效',422],
        NotFoundHttpException::class=>['没有找到该页面',404],
        MethodNotAllowedHttpException::class=>['访问方式不正确',405],
        QueryException::class=>['参数错误',401],
    ];
}

Handler

<?php

namespace App\Exceptions;

use App\Api\Helpers\ExceptionReport;
use App\Api\Utils\Util;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */ 
    protected $dontReport = [
        //
//        \League\OAuth2\Server\Exception\OAuthServerException::class,

    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */ 
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */ 
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });

        $this->renderable(function (ValidationException $e, $request) {
            return response()->json(Util::JsonDataArr(400,$e->getMessage()));
        });

        $this->renderable(function (AuthenticationException $e, $request) {
            Log::error($e->getMessage(), ['AuthenticationException']);
            return response()->json($this->getMessageError(AuthenticationException::class));
        });

        $this->renderable(function (ModelNotFoundException $e, $request) {
            return response()->json($this->getMessageError(ModelNotFoundException::class));
        });

        $this->renderable(function (AuthorizationException $e, $request) {
            return response()->json($this->getMessageError(AuthorizationException::class));
        });

        $this->renderable(function (UnauthorizedHttpException $e, $request) {
            return response()->json($this->getMessageError(UnauthorizedHttpException::class));
        });

        $this->renderable(function (NotFoundHttpException $e, $request) {
            return response()->json($this->getMessageError(NotFoundHttpException::class));
        });

        $this->renderable(function (MethodNotAllowedHttpException $e, $request) {
            return response()->json($this->getMessageError(MethodNotAllowedHttpException::class));
        });

        $this->renderable(function (QueryException $e, $request) {
            return response()->json($this->getMessageError(QueryException::class));
        });
    }

    private function getMessageError($class)
    {
        $message = ExceptionReport::$doReportOther[$class];
        return Util::JsonDataArr(400, $message[0]);

    }
}

结论

  • 大概方式就是这样, 有更好的方式欢迎提出