hyperf框架基础建设:自定义异常捕获

2 篇文章 0 订阅
2 篇文章 0 订阅

通常项目开发过程中会有很多场景下的异常处理,以接口参数验证异常处理为例

1.定义异常处理器(ValidateExceptionHandler.php):App\Exception\Handler\ValidateExceptionHandler::class

<?php

namespace App\Exception\Handler;

use App\Exception\ValidateException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class ValidateExceptionHandler extends ExceptionHandler
{

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        // 判断被捕获到的异常是希望被捕获的异常
        if ($throwable instanceof ValidateException) {
            // 格式化输出
            $data = json_encode([
                'code' => (string)$throwable->getCode(),
                'message' => $throwable->getMessage(),
                'data' => [],
            ], JSON_UNESCAPED_UNICODE);

            // 阻止异常冒泡
            $this->stopPropagation();
            return $response->withAddedHeader('content-type', 'application/json; charset=utf-8')->withBody(new SwooleStream($data));
        }

        // 交给下一个异常处理器
        return $response;

        // 或者不做处理直接屏蔽异常
    }

    /**
     * 判断该异常处理器是否要对该异常进行处理
     */
    public function isValid(Throwable $throwable): bool
    {
        return true;
    }


}

2.定义异常类(ValidateException.php):App\Exception\ValidateException::class

<?php

namespace App\Exception;

use App\common\response\SystemCode;
use Hyperf\Server\Exception\ServerException;
use Throwable;

class ValidateException extends ServerException
{

    public function __construct($message = "验证类错误", $code = SystemCode::SYSTEM_ERROR, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }

}

3.注册异常处理器(exceptions.php)

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
return [
    'handler' => [
        'http' => [
            App\Exception\Handler\HttpExceptionHandler::class,
            //Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class,//默认的
            App\Exception\Handler\ValidateExceptionHandler::class,
            App\Exception\Handler\AppExceptionHandler::class,


        ],
    ],
];

4.使用

throw new ValidateException($res["data"],SystemCode::SYSTEM_ERROR_PARAM_NULL);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值