异常
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user