您好,欢迎访问一九零五行业门户网

Lumen如何实现类Laravel5用户友好的错误页面

laravel5实现用户友好的错误页面非常简单,例如想要返回status 404,只需要在view/errors中添加一个404.blade.php文件即可。lumen中没有默认实现这种便利,于是自己添加一个。
lumen如何实现类laravel5用户友好的错误页面 原理 抛出错误的函数是abort(), 进入该函数一看究竟,会发现只是抛出一个httpexception. 在application中,处理http request的时候,有一个try catch的过程,exception就是在这里被捕获的。
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);}
接着可以看出,exception是交给了sendexceptiontohandler去处理了。这里的handler具体是哪个类呢?是实现了illuminate\contracts\debug\exceptionhandler的一个单例。为啥说他是单例?因为在bootstrap的时候,已经初始化为单例了,请看。
$app->singleton( illuminate\contracts\debug\exceptionhandler::class, app\exceptions\handler::class);
进入该类看一下,他有一个render方法,好吧,找到问题所在了,修改一下这个方法即可。
public function render($request, exception $e){ return parent::render($request, $e);}
动手修改 由于laravel已经有实现了,所以最简便的方法就是复制黏贴。在render中先判断下是否为httpexception, 如果是,就去errors目录下找对应status code的view,如果找到,就渲染它输出。就这么简单。修改handler如下:
/** * 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;}
好了,在errors目录下新建一个404.blade.php文件,在controller中尝试 abort(404)看一下吧。
其它类似信息

推荐信息