Flask-restful - 在处理上述异常的过程中,发生了另一个异常

Flask-restful - During handling of the above exception, another exception occurred

作为 Flask 的一部分-restful API 我有一个登录资源:

class LoginApi(Resource):
    def post(self):
        try:
            body = request.get_json()
            user = User.objects.get(email=body.get('email'))
            authorized = user.check_password(body.get('password'))
            if not authorized:
                raise UnauthorizedError
            expires = datetime.timedelta(days=7)
            access_token = create_access_token(identity=str(user.id), expires_delta=expires)
            return {'token': access_token}, 200
        except DoesNotExist:
            raise UnauthorizedError
        except Exception as e:
            raise InternalServerError

登录路由有4种场景:

  1. 邮箱和密码正确
  2. 数据库中不存在电子邮件 - 在这种情况下会正确引发 UnauthorizedError。
  3. 电子邮件存在但密码不正确 - 在这种情况下我遇到了问题(如下所述)
  4. 一些其他错误 - InternalServerError 正确引发。

所以对于数字 3 - 我没有收到 UnauthorizedError,而是收到了 InternalServerError。

if not authorized: 语句工作正常(如果我在其中打印,我可以看到它工作)。但是由于某种原因,我在尝试引发错误时得到以下信息:

During handling of the above exception, another exception occurred:

我遇到了 this PEP article,这似乎建议更改为 raise UnauthorizedError from None,但问题仍然存在。有谁知道我如何才能成功实施?理想情况下,我希望从场景 2 和场景 3 中引发相同的错误,否则有人可能会从他们返回的错误中知道数据库中是否存在电子邮件。

if 语句正在引发 UnAuthorized,但这发生在 excepts 中,您必须引发 DoesNotExist 才能做到这一点,以便可以在 except 中引发 UnAuthorized。