How does Lumen implement user-friendly error pages like Laravel5?
Laravel5 is very simple to implement user-friendly error pages. for example, to return status 404, you only need to add a 404. blade. php file in view/errors. Lumen does not implement this convenience by default, so you can add one by yourself.
How Lumen implements the principle of user-friendly error pages like Laravel5
The function that throws an error is abort (). when you enter this function, you will find that only an HttpException is thrown. in Application, when processing http requests, there is a try catch process. Exception is captured here.
try { return $this->sendThroughPipeline($this->middleware, function () use ($method, $pathInfo) { if (isset($this->routes[$method.$pathInfo])) { return $this->handleFoundRoute([true, $this->routes[$method.$pathInfo]['action'], []]); } return $this->handleDispatcherResponse( $this->createDispatcher()->dispatch($method, $pathInfo) ); });} catch (Exception $e) { return $this->sendExceptionToHandler($e);}
The Exception is handled by sendExceptionToHandler. Which kind of handler is used here? Is a singleton that implements Illuminate \ Contracts \ Debug \ ExceptionHandler. Why is he a singleton? Because it was initialized as a singleton during bootstrap, please refer.
$app->singleton( Illuminate\Contracts\Debug\ExceptionHandler::class, App\Exceptions\Handler::class);
Go to the class and check it. he has a render method. okay, find the problem and modify it.
public function render($request, Exception $e){ return parent::render($request, $e);}
Manual modification
Since Laravel has already been implemented, the easiest way is to copy and paste. In render, first judge whether it is HttpException. If yes, go to the errors directory to find the view corresponding to the status code. If yes, render the output. That's simple. Modify Handler as follows:
/** * 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( !env('APP_DEBUG') and $this->isHttpException($e)) { return $this->renderHttpException($e); } return parent::render($request, $e);}/** * Render the given HttpException. * * @param \Symfony\Component\HttpKernel\Exception\HttpException $e * @return \Symfony\Component\HttpFoundation\Response */protected function renderHttpException(HttpException $e){ $status = $e->getStatusCode(); if (view()->exists("errors.{$status}")) { return response(view("errors.{$status}", []), $status); } else { return (new SymfonyExceptionHandler(env('APP_DEBUG', false)))->createResponse($e); }}/** * Determine if the given exception is an HTTP exception. * * @param \Exception $e * @return bool */protected function isHttpException(Exception $e){ return $e instanceof HttpException;}
Now, create a new 404. blade. php file in the errors directory, and try abort (404) in the controller.