report 方法用于记录异常 . 默认情况下, the report method passes the exception to the base class 记录异常 . 但是,您可以根据需要自由记录异常 . 例如,如果需要以不同方式报告不同类型的异常,则可以使用PHP instanceof比较运算符
if($exception instanceof PostTooLargeException || $exception instanceof FileException){
return response()->json([
'error' => true,
'error_message' => "The file you are trying to upload exceeds the maximum limit. Please try to upload a smaller file."
],200);
}
3 Answers
Custom HTTP Error Pages
https://laravel.com/docs/5.6/errors#custom-http-error-pages
真的,你想要处理你的例外 . 将代码包装在try catch中,您可以执行各种操作(例如email / slack / log) . 处理完异常后,您仍然可以在catch中使用自定义http错误页面,以便最终用户在设计精美的页面上获得友好消息 . 甚至还内置了一个报告助手,允许您从外部登录并继续处理代码 .
@Devon的上述答案:自定义HTTP错误页面可以为您提供您想要的内容 .
请注意几点:
App\Exceptions\Handler 类是记录应用程序触发的所有异常然后呈现给用户的位置 . 这个类有两个方法 report() 和 render() ,两者都有自己的责任 .
report 方法用于记录异常 . 默认情况下, the report method passes the exception to the base class 记录异常 . 但是,您可以根据需要自由记录异常 . 例如,如果需要以不同方式报告不同类型的异常,则可以使用PHP instanceof比较运算符
render 方法负责将给定的异常转换为应该发送回浏览器的HTTP响应 . 默认情况下,异常将传递给基类,后者会为您生成响应 . 但是,您可以自由检查异常类型或返回自己的自定义响应 .
在您的情况下,您希望返回异常的自定义消息,在 render() 中,您可以使用PHP instanceof比较运算符并返回您自己的逻辑 .
Example :
浏览https://laravel.com/docs/5.6/errors以获取更多数据