自定义 Sanic Exception
Sanic 是一个和类Flask 的基于Python3.5+的web框架,它使用了 Python3 异步特性,有远超 flask 的性能。 编写 RESTful API 的时候,我们会定义特定的异常错误类型,比如我定义的错误返回值格式为: { "error_code": 0, "message": "string", "text": "string" } 不同的错误信息指定不同的 http 状态码。 sanic 提供了几种常用的 exception: NotFound(404) Forbidden(403) ServerError(500) InvalidUsage(400) Unauthorized(401) RequestTimeout(408) PayloadTooLarge(413) 这些 exception 继承自 SanicException 类: class SanicException(Exception): def __init__(self, message, status_code=None): super().__init__(message) if status_code is not None: self.status_code = status_code 从上述代码可以看出,这些异常只能指定 message 和 status_code 参数,那我们可不可以自定义 exception 然后在自定义的 exception 中增加参数呢?下面的代码是按照这个思路修改后的代码: class ApiException(SanicException): def __init__(self, code, message=None, text=None, status_code=None): super().__init__(message) self.error_code = code self.message = message self.text = text if status_code is not None: self.status_code = status_code 使用后我得到一个结果如下: ...