This commit is contained in:
Aether
2025-09-25 10:46:45 +08:00
parent 3c89a01a81
commit db760bb276
4 changed files with 46 additions and 24 deletions

View File

@@ -5,6 +5,8 @@ declare(strict_types=1);
namespace Aether;
use Aether\Exception\BusinessException;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Database\Model\ModelNotFoundException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\MessageInterface;
@@ -15,15 +17,29 @@ use function Hyperf\Support\env;
class GlobalExceptionHandler extends ExceptionHandler
{
protected StdoutLoggerInterface $logger;
public function __construct(StdoutLoggerInterface $logger)
{
$this->logger = $logger; // filter
}
public function handle(Throwable $throwable, ResponseInterface $response): MessageInterface|ResponseInterface
{
// 处理业务异常
if ($throwable instanceof BusinessException) {
$data = [
'code' => $throwable->getCode(),
'message' => $throwable->getMessage(),
'data' => null,
'timestamp' => time(),
Config::RESPONSE_FIELD_KEY_CODE => $throwable->getCode(),
Config::RESPONSE_FIELD_KEY_MESSAGE => $throwable->getMessage(),
Config::RESPONSE_FIELD_KEY_DATA => null,
];
}
// 数据库无记录异常
if ($throwable instanceof ModelNotFoundException) {
$data = [
Config::RESPONSE_FIELD_KEY_CODE => 404,
Config::RESPONSE_FIELD_KEY_MESSAGE => $throwable->getMessage() ?: '没有对应记录',
Config::RESPONSE_FIELD_KEY_DATA => null,
];
} else {
// 记录未知错误日志
@@ -36,15 +52,14 @@ class GlobalExceptionHandler extends ExceptionHandler
));
$data = [
'code' => 500,
'message' => 'Server internal error',
'data' => env('APP_ENV') === 'dev' ? [
Config::RESPONSE_FIELD_KEY_CODE => 500,
Config::RESPONSE_FIELD_KEY_MESSAGE => 'Server internal error',
Config::RESPONSE_FIELD_KEY_DATA => env('APP_ENV') === 'dev' ? [
'message' => $throwable->getMessage(),
'file' => $throwable->getFile(),
'line' => $throwable->getLine(),
'trace' => $throwable->getTraceAsString(),
] : null,
'timestamp' => time(),
];
}