Files
hyperf_data/app/Exception/Handler/BusinessExceptionHandler.php
2025-09-28 14:51:38 +08:00

66 lines
1.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
namespace App\Exception\Handler;
use Aether\AetherResponse;
use Aether\RpcException\BusinessException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;
class BusinessExceptionHandler extends ExceptionHandler
{
/**
* 显式声明next属性确保存在.
*/
protected ?self $next = null;
/**
* 处理异常.
*/
public function handle(Throwable $throwable, ResponseInterface $response)
{
// 只处理BusinessException类型的异常
if ($throwable instanceof BusinessException) {
$result = AetherResponse::error(
$throwable->getCode(),
$throwable->getMessage() ?: '业务处理异常'
);
$body = json_encode($result, JSON_UNESCAPED_UNICODE);
return $response
->withHeader('Content-Type', 'application/json')
->withStatus(200)
->withBody(new SwooleStream((string) $body));
}
// 安全处理下一个处理器
if ($this->next !== null) {
return $this->next->handle($throwable, $response);
}
// 如果没有下一个处理器,直接返回原始响应
return $response;
}
/**
* 判断是否需要处理该异常.
*/
public function isValid(Throwable $throwable): bool
{
return $throwable instanceof BusinessException;
}
/**
* 显式实现setNext方法.
*/
public function setNext(self $handler): void
{
$this->next = $handler;
}
}