博客 / 詳情

返回

Larave開發Dingo處理自定義Exception時render不生效【解決】

1.不使用Dingo Api進自定義Exception的處理方式是

首先定義Exception類,如AppExceptionsApiException

namespace App\Exceptions;

use Exception;
use Throwable;

class ApiException extends Exception
{
    public function __construct(string $message = "", int $code = 1, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }
}   
     

其次在AppExceptionsHandler中針對Exception處理

public function render($request, Exception $exception)

{
    if ($exception instanceof ApiException) {
        return response()->json(['status'=>$exception->getCode(), 'msg'=> $exception->getMessage()]);//自定義返回
    }

    return parent::render($request, $exception);
}

最後在使用時,throw new ApiException('請求出錯', 123);

2.在使用Dingo api處理接口時,發現laravel本身appExceptionsHandler中無法捕獲異常, render無法生效了,原因是Dingo 接管了Exception,解決如下

首先重新定義一個Handler類

namespace App\Exceptions;

use Exception;
use Dingo\Api\Exception\Handler as DingoHandler;

class ApiHandler extends DingoHandler
{
    public function handle(Exception $exception)
    {
        if ($exception instanceof ApiException) {
            return ['status'=>$exception->getCode(), 'msg'=> $exception->getMessage()];//自定義返回,注意此處不能使用response()返回了,因為Dingo封裝處理了,全部當code為500返回,所以此處應直接返回array,

        }
        return parent::handle($exception);
    }
}

其次註冊處理類,可直接在AppProvidersAppServiceProvider->boot函數中添加(本例採用此方法),也可以自定義一個Provider,然後在config/app.php的providers數組中添加進去

    public function boot()
    {
        // 自定義錯誤處理
        $this->app->alias('api.exception', 'App\Exceptions\ApiHandler');

        $this->app->singleton('api.exception', function ($app) {
            return new \App\Exceptions\ApiHandler($app['Illuminate\Contracts\Debug\ExceptionHandler'],
                $app['config']['api.errorFormat'], $app['config']['api.debug']);
        });
    }

最後在使用時,throw new ApiException('請求出錯', 123);

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.