Laravel教程:异常、错误处理
Laravel所有的异常是由 app\Exceptions\Handler 类来处理。 这个类包含两个方法 - report 和 render。
report()方法
report() 方法用于报告或记录异常。 它也可以用来发送日志例外类似 Sentry, Bugsnag 等外部扩展服务
render()方法
render() 方法用来呈现异常到HTTP响应送回浏览器。
除了这两种方法,app\Exceptions\Handler 类包含一个一个重要属性名为 “$dontReport”。此属性采用的异常类型数组将不会被日志记录。
HTTP例外
一些异常描述HTTP错误代码类似:404,500等。要在应用程序中的任何地方产生这样响应,你可以按如下方式使用abort()方法。
abort(404)
自定义错误页
Laravel使得让我们很容易使用每个单独的错误代码来自定义错误页。 例如,如果想设计的自定义页面错误代码:404, 你可以创建一个视图为 :resources/views/errors/404.blade.php。同样的道理,如果你想设计错误代码是500的错误页,它应存放在:resources/views/errors/500.blade.php.
示例
第1步 - 添加以下行到文件 : app/Http/routes.php
Route::get('/error',function(){ abort(404); });
第2步 - 创建一个名为 resources/views/errors/404.blade.php 的视图文件,并复制下面的代码到此文件中。
resources/views/errors/404.blade.php
<!DOCTYPE html> <html> <head> <title>404页面</title> <link href = "https://fonts.googleapis.com/css?family=Lato:100" rel = "stylesheet" type = "text/css"> <style> html, body { height: 100%; } body { margin: 0; padding: 0; width: 100%; color: #B0BEC5; display: table; font-weight: 100; 'Lato'; } .container { text-align: center; display: table-cell; vertical-align: middle; } .content { text-align: center; display: inline-block; } .title { font-size: 72px; margin-bottom: 40px; } </style> </head> <body> <div class = "container"> <div class = "content"> <div class = "title">404 错误</div> </div> </div> </body> </html>
第3步 - 访问以下网址测试事件。
http://localhost:8000/error
第4步 - 访问URL后,您会看到以下输出 -


THE END