laravel9 錯誤處理

wozailu發表於2022-04-16

舊版異常

  • 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 協議》,轉載必須註明作者和本文連結

相關文章