Laravel應(yīng)用中所有的異常都通過 App\Exceptions\[Handler](http://laravelacademy.org/tags/handler "View all posts in Handler")
進(jìn)行處理会前,下面我們先簡單分析下給異常處理器類的屬性和方法:
laravel中針對具體的處理邏輯蔑歌,可能存在的錯誤揣非。try{} catch(Exception $e) {}捕獲處理對應(yīng)的錯誤。針對大量出現(xiàn)的可能存在異常尊流,可以使用全局異常捕獲淀衣,如NotFoundException ,ModelNotFoundException
在\App\Exception\Handle中膘魄,對于不需要處理的異常添加到 $dontReport = []。其中report方法一般是對應(yīng)的分開記錄日志處理竭讳,render方法是對應(yīng)的異常http響應(yīng)處理创葡。
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
}
if ($e instanceof \ErrorException) {
return xxx;
}
}
}
render方法
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
//TODO 這里一條自定義http錯誤自動跳轉(zhuǎn)到首頁
if (getenv('APP_ENV') == 'production' && $e instanceof HttpException) {
Log::error($e);
return Redirect::to('admin/dashboard');
}
if (getenv('APP_ENV') == 'production' && $e instanceof TokenMismatchException) {
Log::error($e);
if ($request->ajax()) {
return Response::json(
[
'status' => 'failed',
'error' =>
[
'status_code' => 401,
'message' => '操作未完成,系統(tǒng)加載失敗绢慢,重新登錄或者刷新當(dāng)前頁面灿渴!'
]
]
);
}
return Redirect::to('admin/logout');
}
return parent::render($request, $e);
}