You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hyperf-gateway/app/Exception/Handler/BusinessExceptionHandler.php

39 lines
1.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Exception\Handler;
use App\Exception\BusinessException;
use App\Helper\Result;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;
class BusinessExceptionHandler extends ExceptionHandler
{
public function handle(Throwable $throwable, ResponseInterface $response)
{
// 判断被捕获到的异常是希望被捕获的异常
if ($throwable instanceof BusinessException) {
// 格式化输出
$data = json_encode(Result::error($throwable->getCode(), $throwable->getMessage()), JSON_UNESCAPED_UNICODE);
// 阻止异常冒泡
$this->stopPropagation();
return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(200)->withBody(new SwooleStream($data));
}
// 交给下一个异常处理器
return $response;
}
/**
* 判断该异常处理器是否要对该异常进行处理
*/
public function isValid(Throwable $throwable): bool
{
return true;
}
}