This repository has been archived on 2024-07-11. You can view files and clone it, but cannot push or open issues or pull requests.
yoshop/source/application/common/exception/ExceptionHandler.php

50 lines
1.2 KiB
PHP
Raw Normal View History

2020-04-25 22:20:29 +08:00
<?php
namespace app\common\exception;
use think\exception\Handle;
use think\Log;
use Exception;
/**
* 重写Handle的render方法实现自定义异常消息
* Class ExceptionHandler
* @package app\common\library\exception
*/
class ExceptionHandler extends Handle
{
private $code;
private $message;
/**
* 输出异常信息
* @param Exception $e
* @return \think\Response|\think\response\Json
*/
public function render(Exception $e)
{
if ($e instanceof BaseException) {
$this->code = $e->code;
$this->message = $e->message;
} else {
if (config('app_debug')) {
return parent::render($e);
}
$this->code = 0;
$this->message = $e->getMessage() ?: '很抱歉,服务器内部错误';
$this->recordErrorLog($e);
}
return json(['msg' => $this->message, 'code' => $this->code]);
}
/**
* 将异常写入日志
* @param Exception $e
*/
private function recordErrorLog(Exception $e)
{
Log::record($e->getMessage(), 'error');
Log::record($e->getTraceAsString(), 'error');
}
}