laravel 异常捕获_Laravel框架捕获各种类型错误
Laravel 中的所有異常都由類App\Exceptions\Handler集中處理,這個類有兩個方法:report 和 render。
【report 方法】
report 方法用于記錄異常并將其發送給外部服務。默認情況下,report 方法只是將異常傳遞給異常基類并寫入日志進行記錄,我們可以在 report 中自定義異常日志記錄行為。
【dontReport 屬性】
異常處理器的 $dontReport 屬性用于定義不進行記錄的異常類型。默認情況下,HttpException 和 ModelNotFoundException 異常不會被記錄,我們可以添加其他需要忽略的異常類型到這個數組。
【render 方法】
render 方法負責將異常轉化為 HTTP 響應。默認情況下,異常會傳遞給 Response 基類生成響應。我們可以 render 方法中進行異常捕獲和返回自定義的 HTTP 響應
本次捕獲主要通過render方法實現,并且定義了一些錯誤等級。
具體代碼如下:
namespace?App\Exceptions;
use?Exception;
use?Illuminate\Database\QueryException;
use?Illuminate\Foundation\Exceptions\Handler?as?ExceptionHandler;
use?Symfony\Component\HttpKernel\Exception\HttpException;
class?Handler?extends?ExceptionHandler
{
protected?$levels?=?[
100?=>?'debug',
200?=>?'info',
300?=>?'notice',
400?=>?'notice',
500?=>?'warning',
600?=>?'error',
700?=>?'critical',
800?=>?'alert',
900?=>?'emergency',
];
protected?$msg?=?[
100?=>?'通信成功',
200?=>?'請求處理成功',
300?=>?'身份驗證失敗',
400?=>?'參數驗證失敗',
500?=>?'請求地址/類型錯誤',
600?=>?'數據庫語句錯誤',
700?=>?'服務端出現異常',
800?=>?'服務超時請重試',
900?=>?'程序錯誤請重試',
];
protected?$code?=?0;
/**
*?A?list?of?the?exception?types?that?are?not?reported.
*
*?@var?array
*/
protected?$dontReport?=?[
//
];
/**
*?A?list?of?the?inputs?that?are?never?flashed?for?validation?exceptions.
*
*?@var?array
*/
protected?$dontFlash?=?[
'password',
'password_confirmation',
];
/**
*?Report?or?log?an?exception.
*
*?@param??\Exception??$exception
*?@return?void
*/
public?function?report(Exception?$exception)
{
parent::report($exception);
}
/**
*?Render?an?exception?into?an?HTTP?response.
*
*?@param??\Illuminate\Http\Request??$request
*?@param??\Exception??$exception
*?@return?\Illuminate\Http\Response
*/
public?function?render($request,?Exception?$exception)
{
if?($exception?instanceof?HttpException)?{
$this->code?=?500;
}
if?($exception?instanceof?QueryException)?{
$this->code?=?600;
}
if?($exception?instanceof?\ReflectionException)?{
$this->code?=?700;
}
if?($exception?instanceof?\RuntimeException)?{
$this->code?=?800;
}
if?($exception?instanceof?\ErrorException)?{
$this->code?=?900;
}
if($this->code){
$result?=?[
'request'?=>$request->input(),
'data'?=>?$exception->getMessage(),
'code'?=>?$this->code,
'msg'?=>?$this->msg[$this->code],
];
\Illuminate\Support\Facades\Log::log($this->levels[$this->code],'Render?Data',$result);
unset($result['request']);
return?response()->json($result,?200);
}
return?parent::render($request,?$exception);
}
}
總結
以上是生活随笔為你收集整理的laravel 异常捕获_Laravel框架捕获各种类型错误的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 结构体中vector自动为0_面试题:你
- 下一篇: 吉大计算机学院刘淑芬,刘淑芬-吉林大学计