Hyperf 异常处理器

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

1.自定义异常

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

touch app/Exception/Handler/JwtExceptionHandler.php

2.JwtExceptionHandler.php文件内容

<?php

namespace App\Exception\Handler;

use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Phper666\JwtAuth\Exception\TokenValidException;
use Psr\Http\Message\ResponseInterface;
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 Hyperf\Validation\ValidationExceptionHandler;

return [
'handler' => [
'http' => [
App\Exception\Handler\AppExceptionHandler::class,
\App\Exception\Handler\JwtExceptionHandler::class,
],
],
];

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

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

posted @ 2021-07-26 17:24  Kris-Q  阅读(330)  评论(0编辑  收藏  举报