hyperf-gateway/app/Exception/Handler/BusinessExceptionHandler.php
2022-11-04 15:37:04 +08:00

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;
}
}