天天看點

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,這就是關于異常的處理。