Hyperf 异常处理器

本文章主要针对token验证的异常处理

1.自定义异常

在项目app/Exception/Handler/下,创建一个JwtExceptionHandler.php文件

touch app/Exception/Handler/JwtExceptionHandler.php

2.JwtExceptionHandler.php文件内容

<?php

namespace AppExceptionHandler;

use HyperfExceptionHandlerExceptionHandler;
use HyperfHttpMessageStreamSwooleStream;
use Phper666JwtAuthExceptionTokenValidException;
use PsrHttpMessageResponseInterface;
use Throwable;

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

// 阻止异常冒泡
$this->stopPropagation();
return $response->withStatus(500)->withBody(new SwooleStream($data));
}

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

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

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

3.注册异常

编辑配置文件 config/autoload/exceptions.php

<?php

declare(strict_types=1);

use HyperfValidationValidationExceptionHandler;

return [
'handler' => [
'http' => [
AppExceptionHandlerAppExceptionHandler::class,
AppExceptionHandlerJwtExceptionHandler::class,
],
],
];

最后测试一下!!ok,这就是关于异常的处理。

如果有其他更好的方法处理异常,请欢迎留言,互相交流进步!!!

原文地址:https://www.cnblogs.com/myJuly/p/15062472.html