This commit is contained in:
Aether
2025-09-25 10:01:34 +08:00
parent 0ca8d067c6
commit 3c89a01a81
4 changed files with 96 additions and 2 deletions

View File

@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Aether;
use Aether\Exception\BusinessException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\MessageInterface;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use function Hyperf\Support\env;
class GlobalExceptionHandler extends ExceptionHandler
{
public function handle(Throwable $throwable, ResponseInterface $response): MessageInterface|ResponseInterface
{
// 处理业务异常
if ($throwable instanceof BusinessException) {
$data = [
'code' => $throwable->getCode(),
'message' => $throwable->getMessage(),
'data' => null,
'timestamp' => time(),
];
} else {
// 记录未知错误日志
$this->logger->error(sprintf(
'Unknown error: %s %s in %s:%d',
$throwable->getMessage(),
$throwable->getCode(),
$throwable->getFile(),
$throwable->getLine()
));
$data = [
'code' => 500,
'message' => 'Server internal error',
'data' => env('APP_ENV') === 'dev' ? [
'message' => $throwable->getMessage(),
'file' => $throwable->getFile(),
'line' => $throwable->getLine(),
'trace' => $throwable->getTraceAsString(),
] : null,
'timestamp' => time(),
];
}
$body = json_encode($data, JSON_UNESCAPED_UNICODE);
return $response->withHeader('Content-Type', 'application/json')
->withBody(new SwooleStream($body));
}
public function isValid(Throwable $throwable): bool
{
return true;
}
}