laravel9 错误处理

旧版异常

  • 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]);

    }
}

结论

  • 大概方式就是这样, 有更好的方式欢迎提出
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 1

可以用断言来判断错误类型,这是可以优化的地方

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!