Files
hyperf_data/extend/Aether/PHP/Hyperf/ApiExceptionHandler.php
2025-09-25 09:12:22 +08:00

44 lines
1.3 KiB
PHP

<?php
declare(strict_types=1);
namespace Aether;
use Hyperf\Context\Context;
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 ApiExceptionHandler extends ExceptionHandler
{
public function handle(Throwable $throwable, ResponseInterface $response): MessageInterface|ResponseInterface
{
// 格式化输出
$data = [
'code' => $throwable->getCode() ?: 500,
'message' => $throwable->getMessage() ?: '服务器内部错误',
'request_id' => Context::get('request_id', ''),
'timestamp' => time(),
];
// 开发环境显示堆栈信息
if (env('APP_ENV') === 'dev') {
$data['trace'] = $throwable->getTraceAsString();
}
$body = json_encode($data, JSON_UNESCAPED_UNICODE);
return $response->withHeader('Content-Type', 'application/json')
->withStatus($data['code'] >= 400 && $data['code'] < 500 ? $data['code'] : 500)
->withBody(new SwooleStream($body));
}
public function isValid(Throwable $throwable): bool
{
return true;
}
}