如何在webapp2中JSON格式化HTTP错误响应



我在应用引擎中使用webapp2进行开发。我想做的是在发生错误时发送一个自定义JSON格式的响应。例如,当请求长度大于阈值时,要使用HTTP 400和响应体

进行响应。
{'error':'InvalidMessageLength'}

在webapp2中,可以选择为某些异常分配错误处理程序。例如:

app.error_handlers[400] = handle_error_400

其中handle_error_400如下:

def handle_error_400(request, response, exception):
    response.write(exception)
    response.set_status(400)

当执行webapp2.RequestHandler.abort(400)时,执行上述代码。

如何根据上述设置动态地具有不同的响应格式(HTML和JSON) ?也就是说,如何可能调用不同版本的handle_error_400函数?

这是一个完整的工作示例,演示了如何对所有类型的错误具有相同的错误处理程序,如果您的URL以/json开始,那么响应将是application/json(使用您的想象力,您如何可以很好地利用request对象来决定您应该提供什么样的响应):

import webapp2
import json
def handle_error(request, response, exception):
  if request.path.startswith('/json'):
    response.headers.add_header('Content-Type', 'application/json')
    result = {
        'status': 'error',
        'status_code': exception.code,
        'error_message': exception.explanation,
      }
    response.write(json.dumps(result))
  else:
    response.write(exception)
  response.set_status(exception.code)
app = webapp2.WSGIApplication()
app.error_handlers[404] = handle_error
app.error_handlers[400] = handle_error

在上面的示例中,您可以通过访问以下url轻松测试不同的行为,这些url将返回404,这是最容易测试的错误:

http://localhost:8080/404
http://localhost:8080/json/404

最新更新