<?php
namespace app;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
use app\service\ErrorLogService;
* 应用异常处理类
*/
class ExceptionHandle extends Handle
{
* 不需要记录信息(日志)的异常类列表
* @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
{
$request = request();
$params = $request->param();
$runtime = round(microtime(true) - app()->getBeginTime(), 10);
$memory_use = (memory_get_usage() - app()->getBeginMem()) / 1024;
if($memory_use > 1024)
{
$memory_use = $memory_use / 1024;
if($memory_use > 1024)
{
$memory_use = number_format($memory_use / 1024, 2).'GB';
} else {
$memory_use = number_format($memory_use, 2).'MB';
}
} else {
$memory_use = number_format($memory_use, 2).'KB';
}
$data = [
'message' => $this->getMessage($exception),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'code' => $this->getCode($exception),
'ip' => $request->ip(),
'uri' => $request->url(),
'request_params' => empty($params) ? '' : (is_array($params) ? json_encode($params, JSON_UNESCAPED_UNICODE) : $params),
'tsc' => number_format($runtime, 6),
'memory_use' => $memory_use,
'add_time' => time(),
];
ErrorLogService::ErrorLogAdd($data);
parent::report($exception);
}
* Render an exception into an HTTP response.
*
* @access public
* @param \think\Request $request
* @param Throwable $e
* @return Response
*/
public function render($request, Throwable $e): Response
{
$token = $request->param('token');
if(IS_AJAX || !empty($token))
{
if($e instanceof ValidateException)
{
$msg = $e->getError();
$code = -422;
}
if($e instanceof HttpException && request()->isAjax())
{
$msg = $e->getMessage();
$code = $e->getStatusCode();
}
if(!isset($code))
{
$code = -500;
}
if(empty($msg))
{
if(method_exists($e, 'getMessage'))
{
$msg = $e->getMessage();
} else {
$msg = '服务器错误';
}
}
header('Content-Type: application/json; charset=utf-8');
exit(json_encode(DataReturn($msg, $code)));
}
return parent::render($request, $e);
}
}
?>