我有一个带有@jwt_required 装饰器的功能。
class Test(Resource):
@jwt_required
def get(self):
return {"test": "ok" }
当设置正确的 HTTP 标头时,它工作正常,即
Authentication: Bearer [TOKEN]
但是当令牌无效/错误或混乱时,会引发 jwt.exceptions.DecodeError :
File "env/lib/python3.6/site-packages/flask_restplus/resource.py", line 44, in dispatch_request
resp = meth(*args, **kwargs)
File "env/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py", line 103, in wrapper
verify_jwt_in_request()
File "env/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py", line 32, in verify_jwt_in_request
jwt_data = _decode_jwt_from_request(request_type='access')
File "env/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py", line 267, in _decode_jwt_from_request
decoded_token = decode_token(encoded_token, csrf_token)
File "env/lib/python3.6/site-packages/flask_jwt_extended/utils.py", line 80, in decode_token
encoded_token, verify=False, algorithms=config.algorithm
File "env/lib/python3.6/site-packages/jwt/api_jwt.py", line 84, in decode
payload, _, _, _ = self._load(jwt)
File "env/lib/python3.6/site-packages/jwt/api_jws.py", line 183, in _load
raise DecodeError('Not enough segments')
jwt.exceptions.DecodeError: Not enough segments
我不能一直依赖客户总是使用正确的令牌。而且我无法捕捉到异常,因为它是在装饰器中引发的,而不是我自己的函数。所以结果是 http 500 错误。我应该如何更优雅地处理异常?