使用Python处理HTTP请求无效输入时如何返回自定义400错误信息
解决方案
该需求完全可以实现。你当前仅返回纯400状态码的原因是直接抛出通用Exception,Web框架默认只会返回标准400状态码,不会把异常内的文本作为响应体返回给客户端,你只需要调整异常抛出逻辑或者直接构造带自定义内容的响应即可。
以下是不同常见Python Web框架的实现示例:
Flask框架实现
from flask import jsonify # 校验逻辑部分 operation = json_object['operationType']['operation'] vendor = json_object['operationType']['vendor'] if operation != "Create": # 返回自定义JSON响应+400状态码 return jsonify({ "error_code": "INVALID_OPERATION", "error_msg": "operation字段仅支持取值为Create", "received_value": operation }), 400 # 成功分支逻辑
FastAPI框架实现
from fastapi import HTTPException # 校验逻辑部分 operation = json_object['operationType']['operation'] vendor = json_object['operationType']['vendor'] if operation != "Create": raise HTTPException( status_code=400, detail={ "error_code": "INVALID_OPERATION", "error_msg": "operation字段仅支持取值为Create", "received_value": operation } ) # 成功分支逻辑
Django框架实现
from django.http import JsonResponse # 校验逻辑部分 operation = json_object['operationType']['operation'] vendor = json_object['operationType']['vendor'] if operation != "Create": return JsonResponse({ "error_code": "INVALID_OPERATION", "error_msg": "operation字段仅支持取值为Create", "received_value": operation }, status=400) # 成功分支逻辑
原生http.server实现
如果你用Python内置的http.server写服务,可以手动构造响应:
import json # 校验逻辑部分 operation = json_object['operationType']['operation'] vendor = json_object['operationType']['vendor'] if operation != "Create": res_data = { "error_code": "INVALID_OPERATION", "error_msg": "operation字段仅支持取值为Create", "received_value": operation } res_bytes = json.dumps(res_data).encode('utf-8') self.send_response(400) self.send_header('Content-Type', 'application/json; charset=utf-8') self.send_header('Content-Length', str(len(res_bytes))) self.end_headers() self.wfile.write(res_bytes) return # 成功分支逻辑
调整后用Postman测试时,除了400状态码,还会在响应体中拿到你自定义的错误提示内容。
内容的提问来源于stack exchange,提问作者Sugata Bagchi
相关产品推荐
相关产品推荐

