- 环境:Python3.10 Flask3.0.2
在Flask的异常基类werkzeug.exceptions.HTTPException
中能看到,该类的get_body()
方法将异常信息拼接成了HTML文本:
def get_body(
self,
environ: WSGIEnvironment | None = None,
scope: dict | None = None,
) -> str:
"""Get the HTML body."""
return (
"<!doctype html>\n"
"<html lang=en>\n"
f"<title>{self.code} {escape(self.name)}</title>\n"
f"<h1>{escape(self.name)}</h1>\n"
f"{self.get_description(environ)}\n"
)
def get_headers(
self,
environ: WSGIEnvironment | None = None,
scope: dict | None = None,
) -> list[tuple[str, str]]:
"""Get a list of headers."""
return [("Content-Type", "text/html; charset=utf-8")]
返回的body信息如下:
如果想要Restful,应该返回Json格式的结果,重写异常类代码如下:
from werkzeug.exceptions import HTTPException
class APIException(HTTPException):
code = 500 # 默认情况下的错误
msg = "Sorry, we make a mistake (^.^)"
error_code = 999 # 自己的错误码
def __init__(self, msg=None, code=None, error_code=None, headers=None):
if code:
self.code = code
if error_code:
self.error_code = error_code
if msg:
self.msg = msg
super(APIException, self).__init__(msg, None)
def get_body(self, environ, scope):
body = dict(
msg=self.msg,
error_code=self.error_code,
# request="POST /v1/client/register"
request=request.method + " " + self.get_url_no_param()
# 让客户端知道是哪一个接口产生的异常
)
text = json.dumps(body)
return text
@staticmethod
def get_url_no_param():
full_path = str(request.full_path)
main_path = full_path.split("?")
return main_path[0]
def get_headers(self, environ, scope):
# Content-Type也需要改
return [("Content-Type", "application/json")]
此时,返回的body是这样的: