From d67b108a921772312785dd862bd66bce5e0cd500 Mon Sep 17 00:00:00 2001 From: Wu Clan Date: Sat, 20 May 2023 23:19:16 +0800 Subject: [PATCH] update token default exception return message (#65) --- backend/app/common/exception/errors.py | 23 ++++++++++---------- backend/app/common/response/response_code.py | 4 ++-- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/backend/app/common/exception/errors.py b/backend/app/common/exception/errors.py index a5f5ed8f..6bf5fb82 100644 --- a/backend/app/common/exception/errors.py +++ b/backend/app/common/exception/errors.py @@ -4,7 +4,7 @@ from typing import Any from fastapi import HTTPException -from backend.app.common.response.response_code import CodeEnum +from backend.app.common.response.response_code import CustomCode class BaseExceptionMixin(Exception): @@ -16,7 +16,14 @@ class BaseExceptionMixin(Exception): class HTTPError(HTTPException): - pass + def __init__(self, *, code: int, msg: Any = None, headers: dict[str, Any] | None = None): + super().__init__(status_code=code, detail=msg, headers=headers) + + +class CustomError(BaseExceptionMixin): + def __init__(self, *, error: CustomCode, data: Any = None): + self.code = error.code + super().__init__(msg=error.msg, data=data) class RequestError(BaseExceptionMixin): @@ -54,12 +61,6 @@ class GatewayError(BaseExceptionMixin): super().__init__(msg=msg, data=data) -class CodeError(BaseExceptionMixin): - def __init__(self, *, error: CodeEnum, data: Any = None): - self.code = error.code - super().__init__(msg=error.msg, data=data) - - class AuthorizationError(BaseExceptionMixin): code = 401 @@ -67,8 +68,8 @@ class AuthorizationError(BaseExceptionMixin): super().__init__(msg=msg, data=data) -class TokenError(BaseExceptionMixin): +class TokenError(HTTPError): code = 401 - def __init__(self, *, msg: str = 'Token is invalid', data: Any = None): - super().__init__(msg=msg, data=data) + def __init__(self, *, msg: str = 'Not authenticated', headers: dict[str, Any] | None = None): + super().__init__(code=self.code, msg=msg, headers=headers or {'WWW-Authenticate': 'Bearer'}) diff --git a/backend/app/common/response/response_code.py b/backend/app/common/response/response_code.py index a55dc15a..3a9aa063 100644 --- a/backend/app/common/response/response_code.py +++ b/backend/app/common/response/response_code.py @@ -3,9 +3,9 @@ from enum import Enum -class CodeEnum(Enum): +class CustomCode(Enum): """ - 错误码 + 自定义错误码 """ CAPTCHA_ERROR = (40001, '图形验证码错误')