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

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

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



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



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)



declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  [email protected]
 * @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);

你可能感兴趣的:(hyperf,异常处理,code码,java,php,json)