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);
}