/** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { // If this exception is listed for code forwarding if ($this->shouldConvertToHttpException($e)) { $e = new HttpException($e->getCode(), $e->getMessage(), $e); } // If the request wants JSON (AJAX doesn't always want JSON) if ($request->wantsJson()) { // Define the response $response = ['errors' => 'Sorry, something went wrong.']; // If the app is in debug mode if (config('app.debug')) { // Add the exception class name, message and stack trace to response $response['exception'] = get_class($e); // Reflection might be better here $response['message'] = $e->getMessage(); $response['trace'] = $e->getTrace(); } // Default response of 400 $status = 400; // If this exception is an instance of HttpException if ($this->isHttpException($e)) { // Grab the HTTP status code from the Exception $status = $e->getStatusCode(); } // Return a JSON response with the response array and status code unset($response['trace']); return response()->json($response, $status); } // Default to the parent class' implementation of handler return parent::render($request, $e); }
/** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { if ($e instanceof NotosException) { $e = new HttpException($e->getStatus(), $e->getMessage(), $e->getPrevious(), [], $e->getCode()); $response = new JsonResponse($e->getMessage(), $e->getStatusCode(), []); $response->exception = $e; return $response; } if ($e instanceof ModelNotFoundException) { $e = new NotFoundHttpException($e->getMessage(), $e); } return parent::render($request, $e); }
/** * Handle an exception and display the correct error message. Firstly check * for a errorXXX.format.twig file, otherwise default to error.html.twig * @param GetResponseEvent $event * @param HttpException $exception * @param string $format */ public function handle(GetResponseEvent $event, $exception, $format = 'html') { $message = $exception->getMessage(); if ($exception instanceof HttpException) { $statusCode = $exception->getStatusCode(); } elseif ($exception instanceof AccessDeniedException) { $statusCode = $exception->getCode(); } else { $statusCode = 500; } $error = FlattenException::create($exception); $baseDirectory = 'AnujNairBundle:Error:'; try { $renderedView = $this->template->render("{$baseDirectory}error{$statusCode}.{$format}.twig", ['statusCode' => $statusCode, 'message' => $message, 'error' => $error]); } catch (\Exception $e) { $renderedView = $this->template->render("{$baseDirectory}error.html.twig", ['statusCode' => $statusCode, 'message' => $message, 'error' => $error]); } $response = Response::create($renderedView, $statusCode); $event->stopPropagation(); $event->setResponse($response); }