hyperf-chat/app/Exception/Handler/JwtAuthExceptionHandler.php

50 lines
1.4 KiB
PHP
Raw Normal View History

2020-11-04 16:47:17 +08:00
<?php
namespace App\Exception\Handler;
use Throwable;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Phper666\JWTAuth\Exception\TokenValidException;
2020-12-19 15:05:28 +08:00
use Hyperf\WebSocketServer\Exception\WebSocketHandeShakeException;
2020-11-04 16:47:17 +08:00
/**
* Class JwtAuthExceptionHandler
2021-04-20 16:30:57 +08:00
*
2020-11-04 16:47:17 +08:00
* @package App\Exception\Handler
*/
class JwtAuthExceptionHandler extends ExceptionHandler
{
public function handle(Throwable $throwable, ResponseInterface $response)
{
// 判断被捕获到的异常是希望被捕获的异常
if ($throwable instanceof TokenValidException) {
// 格式化输出
$data = json_encode([
2021-04-20 16:30:57 +08:00
'code' => $throwable->getCode(),
2020-11-04 16:47:17 +08:00
'message' => $throwable->getMessage(),
2021-04-20 16:30:57 +08:00
'data' => []
2020-11-04 16:47:17 +08:00
], JSON_UNESCAPED_UNICODE);
// 阻止异常冒泡
$this->stopPropagation();
2021-04-22 16:54:01 +08:00
2020-11-04 16:47:17 +08:00
return $response->withAddedHeader('content-type', 'application/json; charset=utf-8')->withStatus(401)->withBody(new SwooleStream($data));
}
return $response;
}
/**
* 判断该异常处理器是否要对该异常进行处理
2020-11-14 23:05:45 +08:00
*
* @param Throwable $throwable
* @return bool
2020-11-04 16:47:17 +08:00
*/
public function isValid(Throwable $throwable): bool
{
return true;
}
}