当前位置: 首页 > 后端技术 > PHP

Larave开发Dingo处理自定义异常时Render不生效【解决】

时间:2023-03-30 05:02:41 PHP

1.不使用DingoApi处理自定义Exception的方法是先定义Exception类,如AppExceptionsApiExceptionnamespaceApp\Exceptions;useException;useThrowable;classApiExceptionextendsException{publicfunction__construct(string$message="",int$code=1,Throwable$previous=null){parent::__construct($message,$code,$previous);}}其次,在AppExceptionsHandler中处理publicfunctionrender($request,Exception$exception)forExceptionif($exceptioninstanceofApiException){returnresponse()->json(['status'=>$exception->getCode(),'msg'=>$exception->getMessage()]);//自定义return}returnparent::render($request,$exception);}最后在使用的时候抛出newApiException('requesterror',123);2.使用Dingoapi处理接口时,发现laravel自带的appExceptionsHandler无法捕获异常,render无法生效是的,原因是Dingo接管了Exception,解决方法如下首先重新定义处理程序类命名空间App\Exceptions;使用异常;使用Dingo\Api\Exception\Handler作为DingoHandler;ApiHandler类扩展DingoHandler{publicfunctionhandle(Exception$exception){if($exceptioninstanceofApiException){return['status'=>$exception->getCode(),'msg'=>$exception->getMessage()];//自定义返回,注意this不能用response()返回,因为Dingo已经打包处理了,code为500时全部返回,所以这里应该直接返回数组,}returnparent::handle($exception);其次,注册处理类,可以直接在AppProvidersAppServiceProvider->boot函数中添加(本例中使用该方法),也可以自定义一个Provider,然后添加到config/app的providers数组中。phppublicfunctionboot(){//自定义错误处理$this->app->alias('api.exception','App\Exceptions\ApiHandler');$this->app->singleton('api.exception',function($app){returnnew\App\Exceptions\ApiHandler($app['Illuminate\Contracts\Debug\ExceptionHandler'],$app['配置']['api.errorFormat'],$app['config']['api.debug']);});}最后,使用的时候,thrownewApiException('requesterror',123);