request()->except($this->dontFlash), ]); } catch (Throwable $e) { return []; } } /** * Register the exception handling callbacks for the application. * * @return void */ public function register() { $this->map(ModelNotFoundException::class, function ($e) { $resource = __($key = 'models.'.$e->getModel()); if ($key === $resource) { $resource = str_ireplace(['App\\Models\\Admin\\', 'App\\Models\\'], '', $e->getModel()); } return new HttpException(404, __(':resource not found', ['resource' => $resource]), $e); }); $this->reportable(function (NoGatewayAvailableException $e) { foreach ($e->getExceptions() as $exception) { $this->report($exception); } return false; }); $this->renderable(function (BizException $e, $request) { if ($this->shouldReturnJson($request, $e)) { return response()->json($this->convertExceptionToArray($e), $e->status); } if (! config('app.debug')) { $e = new HttpException($e->status, $e->getMessage(), $e); } return $this->prepareResponse($request, $e); }); } /** * {@inheritdoc} */ protected function unauthenticated($request, AuthenticationException $exception) { return $this->shouldReturnJson($request, $exception) ? response()->json([ 'errcode' => 401, 'message' => $exception->getMessage(), ], 401) : redirect()->guest($exception->redirectTo() ?? route('login')); } /** * {@inheritdoc} */ protected function invalidJson($request, ValidationException $exception) { return response()->json([ 'errcode' => 422, 'message' => $exception->getMessage(), 'errors' => $exception->errors(), ], $exception->status); } /** * {@inheritdoc} */ protected function convertExceptionToArray(Throwable $e) { $data = [ 'errcode' => 500, 'message' => config('app.debug') ? $e->getMessage() : '服务器繁忙,请稍后再试', ]; if ($this->isBizException($e)) { $data = [ 'errcode' => $e->getCode(), 'message' => $e->getMessage(), ]; } elseif ($this->isHttpException($e)) { $data = [ 'errcode' => $e->getStatusCode(), 'message' => $e->getMessage(), ]; } return array_merge(parent::convertExceptionToArray($e), $data); } /** * 确认给定的异常是否是自定义业务异常 * * @param Throwable $e * @return bool */ protected function isBizException(Throwable $e): bool { return $e instanceof BizException; } }