笔记:异常处理之report与render
正常web应用部署在生产环境,都必须关闭调试模式,env配置:
APP_ENV=production
APP_DEBUG=false
所以我们就需要对线上的一些报错进行拦截处理,此处以常见的sql异常错误为例。
代码路径:app/Exceptions/Handler.php
说明:
report 方法用于将错误记录到日志文件中(或一些其他操作),注意 dontReport 属性,它设置不应该被记录到日志的异常类。
render 方法是用于将错误渲染(视图或JSON API),当异常发生时,这个方法应响应相关信息给用户。
<?php
namespace App\Exceptions;
use App\Service\HttpService;
use Exception;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of exception types with their corresponding custom log levels.
*
* @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
*/
protected $levels = [
//
];
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<\Throwable>>
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
/**
* 自定义处理异常返回
*/
public function report(Throwable $exception)
{
return parent::report($exception);
}
/**
* 自定义处理异常返回
* 可按需针对不同异常进行拦截
*/
public function render($request, Throwable $e)
{
//线上关闭 debug
if (!config('app.debug')) {
if ($e instanceof QueryException) {
return HttpService::error('Sql出现未知错误');
}
if ($e instanceof Exception) {
$code = $e->getCode();
$msg = $e->getMessage();
return HttpService::error($msg, [], $code);
}
}
return parent::render($request, $e);
}
}
附:HttpService 为同一的接口响应类。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: