【问题标题】:Python | return 400 through custom exception [duplicate]蟒蛇 |通过自定义异常返回 400 [重复]
【发布时间】:2019-01-15 17:08:42
【问题描述】:

我编写了一个自定义异常处理类来验证输入请求数据并在验证失败时将其提升。这是一个 Flask 应用程序。这似乎一直有效,直到服务器尚未发送响应,因为我可以看到异常对象有一个自定义错误,但随后它被转换为通用 500 错误消息。我错过了什么做错了吗?

class CustException(Exception):
    pass

class APIException(CustException):
    def __init__(self, status=None, title=None, type=None, detail=None, **kwargs):
        super(AIVException, self).__init__(detail)
        self.status = status
        self.detail = detail
        self.title = title
        self.type = type

if x not in [1, 2]:
    raise APIException(status=400, title='Bad request', type=default_type, detail="pass the correct value")

**

注意 - 我希望通过引发异常而不是使用 错误处理程序。所以请不要将其标记为重复。

**

【问题讨论】:

  • 为什么超类没有构造函数的时候有.__init__(detail)
  • 我尝试了一些组合,所以错误地留下了。但不影响响应。不是吗?
  • 因此,如果语法有错误,您会看到 500 错误。尝试使用 .__init__() 而不是 .__init__(detail) 看看你是否仍然得到 500
  • @AbtPst - 删除超级呼叫后不起作用。
  • 可以保留super调用,但构造函数要为空

标签: python flask


【解决方案1】:

如果您想使用 APIException 返回自定义消息或其他内容,可以使用 errorhandler 装饰器

@app.errorhandler(APIException)
def api_exception(ex):
    return 'Your custom message', your_code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 2017-08-17
    • 2020-11-25
    • 2011-06-07
    • 2019-08-31
    • 2017-02-22
    相关资源
    最近更新 更多