Larave开发Dingo处理自定义Exception时render不生效【解决】

1.不使用Dingo Api进自定义Exception的处理方式是php

首先定义Exception类,如AppExceptionsApiExceptionlaravel

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处理json

public function render($request, Exception $exception)api

{
    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,解决以下app

首先从新定义一个Handler类ide

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);this

相关文章
相关标签/搜索