Laravel在默认情况下是开启调试模式的(开启或者关闭调试模式修改.env文件中的APP_DEBUG选项值),如果有遇到报错,会把详细的错误信息显露出来,我们在生产环境肯定不能让这种事发生。

例如访问了非法链接:

如果你把调试模式关闭,访问非法链接显示:

Sorry, the page you are looking for could not be found.

但是,我们可以选择自定义错误页面。下面我们看下修改的方法

Laravel的异常报错是在app/Exception/Handler.php中处理,我们修改这个文件

代码示例:

<?php

namespace App\Exceptions;

use Exception;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\Debug\ExceptionHandler as SymfonyDisplayer;  //新增

class Handler extends ExceptionHandler
{
		/**
		 * A list of the exception types that should not be reported.
		 *
		 * @var array
		 */
		protected $dontReport = [
				HttpException::class,
		];

		/**
		 * Report or log an exception.
		 *
		 * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
		 *
		 * @param  \Exception  $e
		 * @return void
		 */
		public function report(Exception $e)
		{
				return parent::report($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)
		{
				return parent::render($request, $e);
		}
		
		//重载方法
		protected function convertExceptionToResponse(Exception $e)
		{
				$debug = config('app.debug',false);  //获取配置文件中的debug值,在config/app.php文件中
				if ($debug) {
						return (new SymfonyDisplayer($debug))->createResponse($e);
				}
				return response()->view('errors.default',['exception'=>$e],500);  //自定义错误页面
				// return redirect('/');  //直接跳转到首页
		}
}

然后我们只要在resources/view/errors目录下,增加错误模版,并命名为default.blade.php就可以了。

在访问到非法链接或者其他报错的时候,用户看到的是比较友好的页面,或者给恶意客户直接跳转到首页去。

参考文档:Customizing the default Error Page on Laravel 5.1