65 lines
1.9 KiB
PHP
65 lines
1.9 KiB
PHP
<?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 Psr\Log\LoggerInterface;
|
|
use Throwable;
|
|
|
|
use function Hyperf\support\env;
|
|
|
|
class ApiExceptionHandler extends ExceptionHandler
|
|
{
|
|
|
|
protected LoggerInterface $logger;
|
|
|
|
public function __construct(LoggerInterface $logger)
|
|
{
|
|
$this->logger = $logger;
|
|
}
|
|
|
|
public function handle(Throwable $throwable, ResponseInterface $response): MessageInterface|ResponseInterface
|
|
{
|
|
$this->logger->error($throwable->getMessage());
|
|
// 业务异常
|
|
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;
|
|
}
|
|
}
|