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

Tha*_*ris 4 error-handling google-app-engine json webapp2

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

{'error':'InvalidMessageLength'}
Run Code Online (Sandbox Code Playgroud)

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

app.error_handlers[400] = handle_error_400
Run Code Online (Sandbox Code Playgroud)

handle_error_400如下:

def handle_error_400(request, response, exception):
    response.write(exception)
    response.set_status(400)
Run Code Online (Sandbox Code Playgroud)

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

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

Lip*_*pis 5

这是一个完整的工作示例,演示如何为所有类型的错误设置相同的错误处理程序,如果您的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
Run Code Online (Sandbox Code Playgroud)

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

http://localhost:8080/404
http://localhost:8080/json/404
Run Code Online (Sandbox Code Playgroud)