因为在laravel框架中,异常都是通过App\Exceptions\Handler类来处理的,使用instanceof 比较运算符可以判断是否是某个具体的异常,重写类中的render方法,如下:
public function render($request, Exception $exception)
{
/* 错误页面 */
if ($exception instanceof NotFoundHttpException) {
$code = $exception->getStatusCode();
if (view()->exists('errors.' . $code)) {
return response()->view('errors.' . $exception->getStatusCode());
}
}
return parent::render($request, $exception);
}
然后在views
目录里建立一个errors
目录,在目录里再新建一个404.blade.php
页面模版,这样再有404错误时就可以使用我们自己定义的404页面