Laravel 中的異常處理

Laravel 中的所有異常都由類App\Exceptions\Handler集中處理,這個(gè)類有兩個(gè)方法:report 和 render。

report 方法

report 方法用于記錄異常并將其發(fā)送給外部服務(wù)。默認(rèn)情況下,report 方法只是將異常傳遞給異常基類并寫入日志進(jìn)行記錄,我們可以在 report 中自定義異常日志記錄行為。

例如,如果你需要針對(duì)不同的異常類型進(jìn)行不同的記錄方式,可使用 PHP 的 instanceof 操作符進(jìn)行判斷:

public function report(Exception $e){
    if ($e instanceof CustomException) {
        // log custom exception
    } elseif ($e instanceof OtherException) {
        // log other exception
    }

    return parent::report($e);
}

dontReport 屬性

異常處理器的 $dontReport 屬性用于定義不進(jìn)行記錄的異常類型。默認(rèn)情況下,HttpException 和 ModelNotFoundException 異常不會(huì)被記錄,我們可以添加其他需要忽略的異常類型到這個(gè)數(shù)組。

render 方法

render 方法負(fù)責(zé)將異常轉(zhuǎn)化為 HTTP 響應(yīng)。默認(rèn)情況下,異常會(huì)傳遞給 Response 基類生成響應(yīng)。我們可以 render 方法中進(jìn)行異常捕獲和返回自定義的 HTTP 響應(yīng):

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

public function render($request, Exception $e){
    if ($e instanceof CustomException) {
        return response()->view('errors.custom', [], 500);
    } elseif ($e instanceof OtherException) {
        return response()->json(['msg'=>'Other Exception'], 401);
    } elseif ($e instanceof NotFoundHttpException) {
        // Your stuff here
    }

    return parent::render($request, $e);
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容