1、如果你只是想拋出404錯誤,debug開關可以滿足你;
理論上你把 debug
關了,線上環境是會自動到 404
的。
是想要「跳轉到 404 頁」還是「顯示 404 頁」?如果是要跳轉的話,請配置 app/Exceptions/handler.php,並在 NotFoundException 被拋出時返回一個 Redirect 響應。
2、如果你想處理異常或自定義異常,可參照如下;
在laravel項目根目錄下的app
下的Exceptions
目錄下的Handler.php
文件;我們可以在這里自定義異常
以及處理異常
;
最常見的莫過於ModelNotFoundException
下面是一個Demo:
route:
xxx.com/article/8
Handler file:
//處理Http響應異常 public function render($request, Exception $e) { switch($e){ //使用類型運算符 instanceof 判斷異常(實例)是否為 ModelNotFoundException case ($e instanceof ModelNotFoundException): //進行異常處理 return $this->renderException($e); break; default: return parent::render($request, $e); } } //處理異常 protected function renderException($e) { switch ($e){ case ($e instanceof ModelNotFoundException): //自定義處理異常,此處我們返回一個404頁面 return view('errors.404'); break; default: //如果異常非ModelNotFoundException,我們返回laravel默認的錯誤頁面 return (new SymfonyDisplayer(config('app.debug'))) ->createResponse($e); } }
通過上述案例,你可以輕松的處理異常,並給用戶一個友好的提示!
轉:https://segmentfault.com/q/1010000007262633?_ea=1294797