JWT异常处理

zhanqi123

因为要拿到 JWT异常处理反馈的结果 在进行逻辑处理。但是返回的异常很不友好。 不能用。 有什么好的办法?

2921 2 2
2个回答

zhanqi123

没有大神回答吗。 急用。 谢了

  • Tinywan 2022-04-07

    自己处理异常

  • zhanqi123 2022-04-07

    这种返回的异常怎么拿来做判断呀。 有具体方法吗?

  • Tinywan 2022-04-07

    使用try catch 捕捉呀。实在不知道怎么搞,可以安装这个异常插件,自动帮你接管异常:https://www.workerman.net/plugin/16

  • ranen1024 2022-04-09
    1. 新建app/exception/Handle.php
      <?php declare(strict_types=1);

    namespace App\exception;

    use Throwable;
    use Webman\Exception\ExceptionHandler;
    use Webman\Http\Request;
    use Webman\Http\Response;

    class Handler extends ExceptionHandler
    {

    public function report(Throwable $e)
    {
        // TODO: Implement report() method.
    }
    
    public function render(Request $request, Throwable $e): Response
    {
        if ($e instanceof JwtTokenException) {
            return json([
                'code' => $e->getCode(),
                'msg' => $e->getMessage()
            ]);
        }
       // 处理其他异常
        return parent::render($request, $e);
    }

    }

    1. 修改config/exception.php
      [exception.php]
      <?php

    return [
    '' => \App\exception\Handler::class,
    ];

  • zhanqi123 2022-04-11

    我是直接用try 捕捉的

  • ranen1024 2022-04-11

    可以的

  • 王小大 2022-08-17

    不能用来捕获 plugin/webman/gateway/Events.php 下的异常嘛

  • Tinywan 2022-08-17

    应该是可以的

  • 王小大 2022-08-17

    测试了 不行

Tinywan

请问token错误如何返回自己的message格式,而不是返回异常?

1、通过官方异常处理(推荐)

class Handler extends ExceptionHandler
{
    public function render(Request $request, Throwable $e): Response
    {
        if ($e instanceof Tinywan\Jwt\Exception\JwtTokenException) {
            // 返回自己自定义的message格式
            return json([
                'code' => $e->getCode(),
                'msg' => $e->getMessage()
            ]);
        }
       // 处理其他异常
        return parent::render($request, $e);
    }
}

2、通过try catch捕捉

try {
    $uid = JwtToken::getCurrentId();
} catch (Tinywan\Jwt\Exception\JwtTokenException $exception) {
    // 返回自己自定义的message格式
    return json(['code' => 0,'message' => $exception->getMessage()]);
}
  • 暂无评论
年代过于久远,无法发表回答
🔝