:::
13-1 優雅的異常處理
- 那怎樣做才能讓異常狀況不那麼怵目驚心,甚至讓使用者可以知道,現在到底發生了什麼事?首先,我們在終端機,利用
make:exception來建立一個自訂的異常處理php artisan make:exception CustomException - 這時會產生一個
\專案\app\Exceptions\CustomException.php,我們將該檔案修改成如下:<?php namespace App\Exceptions; use Exception; use Illuminate\Http\Request; class CustomException extends Exception { public function render(Request $request) { return view('error', ['msg' => $this->getMessage()]); } }Laravel 5.5 之後支持在異常類中定義
render()方法,該異常被觸發時系統會調用render()方法來輸出,我們在render()裡直接傳回錯誤訊息msg到一個錯誤頁面error.blade.php。 - 此外,由於觸發異常時,Laravel會將之紀錄到log中,如果這種異常無關緊要,不想要紀錄到log裡,可以開啟
\專案\app\Exceptions\Handler.php,將該物件加入$dontReport中即可:<?php namespace App\Exceptions; use Exception; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; class Handler extends ExceptionHandler { /** * A list of the exception types that are not reported. * * @var array */ protected $dontReport = [ CustomException::class, ]; ...略... } - 然後,修改控制器裡面用來執行顯示詳情頁動作的
show()。我們在裡面,偵測on_sale如果不是true,那麼,要拋出一個異常,可以這樣寫(上面別忘了use App\Exceptions\CustomException;):use App\Exceptions\CustomException; ...略... public function show($id) { $product = Product::find($id); if (!$product->on_sale) { throw new CustomException('商品未上架'); } return view('product.show', compact('product')); } - 最後,我們只要建立畫面,接收異常類傳回的訊息即可。
@extends('layouts.app') @section('content') <div class="alert alert-danger text-center"> <h1>{{ $msg }}</h1> </div> <div class="text-center"> <a class="btn btn-primary" href="/">回首頁</a> </div> @endsection - 如此,看到的畫面是這樣:

13. 一般的異常處理
