You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
2.2 KiB
82 lines
2.2 KiB
<?php
|
|
|
|
namespace app\exception;
|
|
|
|
use think\db\exception\DataNotFoundException;
|
|
use think\db\exception\ModelNotFoundException;
|
|
use think\Exception;
|
|
use think\exception\Handle;
|
|
use app\exception\HttpException;
|
|
use think\exception\HttpResponseException;
|
|
use think\exception\ValidateException;
|
|
use think\Response;
|
|
use Throwable;
|
|
|
|
/**
|
|
* 应用异常处理类
|
|
*/
|
|
class ExceptionHandle extends Handle
|
|
{
|
|
|
|
private $httpStatusCode = 200; //http状态码
|
|
|
|
private $msg = '未知错误'; //自定义错误内容
|
|
|
|
private $code = 100; //自定义错误码
|
|
|
|
/**
|
|
* 不需要记录信息(日志)的异常类列表
|
|
* @var array
|
|
*/
|
|
protected $ignoreReport = [
|
|
HttpException::class,
|
|
HttpResponseException::class,
|
|
ModelNotFoundException::class,
|
|
DataNotFoundException::class,
|
|
ValidateException::class,
|
|
];
|
|
|
|
/**
|
|
* 记录异常信息(包括日志或者其它方式记录)
|
|
*
|
|
* @access public
|
|
* @param Throwable $exception
|
|
* @return void
|
|
*/
|
|
public function report(Throwable $exception): void
|
|
{
|
|
// 使用内置的方式记录异常日志
|
|
parent::report($exception);
|
|
}
|
|
|
|
/**
|
|
* Render an exception into an HTTP response.
|
|
* throw new \app\exception\HttpException(309, ''); http使用方法
|
|
* throw new Exception('导演',300); 异常类使用访求
|
|
* @access public
|
|
* @param \think\Request $request
|
|
* @param Throwable $e
|
|
* @return Response
|
|
*/
|
|
public function render($request, Throwable $e): Response
|
|
{
|
|
// 其他错误交给系统处理
|
|
if (config('app.app_debug')) {
|
|
return parent::render($request, $e);
|
|
}
|
|
// 添加自定义异常处理机制
|
|
$this->msg = $e->getMessage() ?: $this->msg;
|
|
//兼容Exception类 这个类没有getStatusCode方法
|
|
if ($e instanceof HttpException) {
|
|
$this->httpStatusCode = $e->getStatusCode() ?: $this->httpStatusCode;
|
|
}
|
|
$this->code = $e->getCode() ?: $this->code;
|
|
$data = [
|
|
'msg' => $this->msg,
|
|
'data' => [],
|
|
'code' => $this->code,
|
|
];
|
|
return json($data, $this->httpStatusCode);
|
|
|
|
}
|
|
}
|
|
|