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);
相关推荐
liuxudong00 2020-11-19
wwzaqw 2020-11-11
lihaoxiang 2020-11-05
CrossingX 2020-11-04
xuegangic 2020-10-17
86417413 2020-11-25
83206733 2020-11-19
86276537 2020-11-19
83266337 2020-11-19
86256434 2020-11-17
zhouboxiao 2020-11-16
rise 2020-11-22
sssdssxss 2020-11-20
windle 2020-11-10
孙雪峰 2020-10-30
xfcyhades 2020-11-20
cheidou 2020-11-19