42 lines
1.1 KiB
PHP
42 lines
1.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Aether;
|
|
|
|
use Hyperf\Context\ApplicationContext;
|
|
use Hyperf\Context\Context;
|
|
use Hyperf\ExceptionHandler\ExceptionHandler;
|
|
use Hyperf\Rpc\Protocol;
|
|
use Psr\Container\ContainerExceptionInterface;
|
|
use Psr\Container\NotFoundExceptionInterface;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Throwable;
|
|
|
|
class RpcExceptionHandler extends ExceptionHandler
|
|
{
|
|
/**
|
|
* @throws ContainerExceptionInterface
|
|
* @throws NotFoundExceptionInterface
|
|
*/
|
|
public function handle(Throwable $throwable, ResponseInterface $response): ResponseInterface
|
|
{
|
|
// 微服务间调用返回更精简的错误信息
|
|
$data = [
|
|
'code' => $throwable->getCode() ?: 500,
|
|
'message' => $throwable->getMessage() ?: '服务调用失败',
|
|
'request_id' => Context::get('request_id', ''),
|
|
];
|
|
|
|
$protocol = ApplicationContext::getContainer()->get(Protocol::class);
|
|
$response->getBody()->write($protocol->pack($data));
|
|
|
|
return $response;
|
|
}
|
|
|
|
public function isValid(Throwable $throwable): bool
|
|
{
|
|
return true;
|
|
}
|
|
}
|