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

本文介绍了在项目开发中如何处理接口参数验证异常。通过创建自定义异常处理器`ValidateExceptionHandler`,捕获并格式化返回`ValidateException`异常的信息,确保返回的数据为JSON格式。同时定义了`ValidateException`类,继承自`ServerException`,用于抛出验证错误。在`exceptions.php`配置文件中注册了异常处理器,确保在出现验证异常时能被正确处理。示例代码展示了异常处理流程,并给出了抛出验证异常的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值