This commit is contained in:
Aether
2025-09-28 14:51:38 +08:00
parent afd384a52a
commit 10b58a8c6d
8 changed files with 326 additions and 4 deletions

View File

@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace Aether\RpcException;
use Aether\Config;
use App\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 ApiExceptionHandler extends ExceptionHandler
{
public function handle(Throwable $throwable, ResponseInterface $response): MessageInterface|ResponseInterface
{
// 业务异常
if ($throwable instanceof BusinessException) {
$code = $throwable->getCode();
$message = $throwable->getMessage();
$data = $throwable->getData();
} else {
// 其他异常
$code = $throwable->getCode(); // ErrorCode::SYSTEM_ERROR;
$data = env('APP_ENV') === 'dev' ? [
'trace' => $throwable->getTraceAsString(),
'file' => $throwable->getFile(),
'line' => $throwable->getLine(),
] : [];
$message = env('APP_ENV') === 'dev' ? $throwable->getMessage() : ErrorCode::getMessage($code);
}
$result = [
Config::RESPONSE_FIELD_KEY_CODE => $code,
Config::RESPONSE_FIELD_KEY_DATA => $data,
Config::RESPONSE_FIELD_KEY_MESSAGE => $message,
];
$body = new SwooleStream(json_encode($result, JSON_UNESCAPED_UNICODE));
return $response->withHeader('Content-Type', 'application/json')
->withStatus(200)
->withBody($body);
}
public function isValid(Throwable $throwable): bool
{
return true;
}
}