Laravel应用中所有的异常都通过 App\Exceptions\[Handler](http://laravelacademy.org/tags/handler "View all posts in Handler")
进行处理,下面我们先简单分析下给异常处理器类的属性和方法:
laravel中针对具体的处理逻辑,可能存在的错误。try{} catch(Exception $e) {}捕获处理对应的错误。针对大量出现的可能存在异常,可以使用全局异常捕获,如NotFoundException ,ModelNotFoundException
在\App\Exception\Handle中,对于不需要处理的异常添加到 $dontReport = []。其中report方法一般是对应的分开记录日志处理,render方法是对应的异常http响应处理。
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错误自动跳转到首页
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' => '操作未完成,系统加载失败,重新登录或者刷新当前页面!'
]
]
);
}
return Redirect::to('admin/logout');
}
return parent::render($request, $e);
}
网友评论