Files
hyperf_service/app/Exception/Handler/ErrExceptionHandler.php
2025-03-10 09:43:27 +08:00

62 lines
1.8 KiB
PHP

<?php
namespace App\Exception\Handler;
use App\Exception\ErrException;
use App\Lib\AdminReturn;
use App\Lib\ApiReturn;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\HttpServer\Request;
use Psr\Http\Message\ResponseInterface;
use Throwable;
class ErrExceptionHandler extends ExceptionHandler
{
/**
* 注入
* @param Request $request
* @param AdminReturn $adminReturn
* @param ApiReturn $apiReturn
*/
public function __construct(
private readonly Request $request,
private readonly AdminReturn $adminReturn,
private readonly ApiReturn $apiReturn,
) {}
/**
* admin控制器异常处理
* @param Throwable $throwable
* @param ResponseInterface $response
* @return ResponseInterface
*/
public function handle(Throwable $throwable, ResponseInterface $response): ResponseInterface
{
if ($throwable instanceof ErrException) {
$urlArr = explode('/',$this->request->path());
$result = match ($urlArr[0]) {
'api' => $this->apiReturn->error($throwable->getMessage(),$throwable->getCode()),
'admin', 'common' => $this->adminReturn->error($throwable->getMessage(),$throwable->getCode()),
default => null,
};
// 阻止异常冒泡
$this->stopPropagation();
if (!empty($result)) {
return $response->withHeader("Content-Type", "application/json")
->withStatus(200)
->withBody(new SwooleStream(json_encode($result, JSON_UNESCAPED_UNICODE)));
}
}
// 交给下一个异常处理器
return $response;
}
public function isValid(Throwable $throwable): bool
{
return true;
}
}