1. 程式人生 > 實用技巧 >laravel 學習筆記之 錯誤和異常

laravel 學習筆記之 錯誤和異常

錯誤和異常

laravel 預設配置了一個錯誤和異常處理類 app\exceptions\handler 用來記錄應用程式處罰的所有異常

配置

在 config\app.php 檔案的 debug 選項中,開發環境 APP_DEBUG 的值應為 true,生產環境 APP_DEBUG 的值應為 false

異常處理

系統所有的異常都由 app\exceptions\handler 類處理,包含兩個方法:report 和 render

report 方法

report 方法將異常資訊記錄日誌,或者傳送給第三方異常資訊處理服務。如果需要處理不同型別的異常,可以使用 php 的型別運算子 instanceof

public function report(Throwable $exception)
{
    if ($exception instanceof CustomException){
        //
    }
    parent::report($exception);
}

不建議在 report 方法中進行太多的 instanceof 檢查,應該使用portable & Renderable 異常

report 輔助函式

report 輔助函式允許你使用異常處理器的 report 方法在不顯示錯誤頁面的情況下快速報告異常

render 方法

render 方法將異常資訊輸出到瀏覽器展示,預設生成的是響應的基類,也可以根據不同型別的異常返回自定義響應

public function render($request, Throwable $exception)
{
    //當丟擲一個 CustomException 時,返回 json 格式的 response
    if ($exception instanceof CustomException){
        return response()->json(['code'=>$exception->getCode(),'msg'=>$exception->getMessage()]);
    }
    return parent::render($request, $exception);
}

Reportable & Renderable 異常

使用 php artisan make:exception YourException 建立一個自定義異常類 YourException,可以直接在該類中定義 report 和 render 方法,框架會自動呼叫這些方法

//當丟擲一個 CustomException 時,會自動執行 CustomException 類的 render 方法
public function render($request, Throwable $e)
{
    return response()->json(['code'=>$e->getCode(),'msg'=>$e->getMessage()]);
}

HTTP 異常

手動丟擲異常

abort(404,'page not find');

建立一個 resources/views/errors/404.blade.php 檢視檔案,由 abort 函式引發的 HttpException 例項將作為 $exception 變數傳遞給檢視

<h2>{{ $exception->getMessage() }}</h2>

使用 vendor:publish Artisan 命令來定義錯誤模板頁面

php artisan vendor:publish --tag=laravel-errors