自定义HTTP错误页面
描述:自定义错误页面,例如404页面不存在、500服务器错误...
解决:
Larave5中自定义错误与异常的处理位于app/Exceptions/Handler.php
/**
* 在HTTP响应中回执异常页面
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
if($this->isHttpException($exception)){
//对于HTTP异常,如404、503等,调用的是renderHttpException()
return $this->renderHttpException($exception);
}else{
return parent::render($request, $exception);
}
}
renderHttpException()
方法位于\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php
文件中
protected function renderHttpException(HttpException $e)
{
$status = $e->getStatusCode();
$paths = collect(config('view.paths'));
view()->replaceNamespace('errors', $paths->map(function ($path) {
return "{$path}/errors";
})->push(__DIR__.'/views')->all());
if (view()->exists($view = "errors::{$status}")) {
return response()->view($view, ['exception' => $e], $status, $e->getHeaders());
}
return $this->convertExceptionToResponse($e);
}
根据代码逻辑,需在\resources\views\
目录下创建errors
目录,存放以错误状态码命名的blade
模板。