How JSON forms an HTTP error response in webapp2

I use webapp2 for development in App Engine. What I would like to do is send an arbitrary formatted JSON response in case of an error. For example, when the request length is greater than the threshold value for an HTTP 400 response and response body

{'error':'InvalidMessageLength'} 

In webapp2, it is possible to assign error handlers for certain exceptions. For instance:

 app.error_handlers[400] = handle_error_400 

Where handle_error_400 is as follows:

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

When webapp2.RequestHandler.abort(400) is executed, the above code is executed.

How can I dynamically create different response formats (HTML and JSON) based on the above setting? That is, how can different versions of the handle_error_400 function be called?

+4
source share
1 answer

Here is a fully working example demonstrating how to have the same error handler for all types of errors, and if your URL starts with /json , then the answer will be application/json (use your imagination about how you could make good use of the object request to determine which answer you should provide):

 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 

In the above example, you can easily test different types of behavior by specifying the following URLs that return 404 , which is the easiest error to check:

 http://localhost:8080/404 http://localhost:8080/json/404 
+5
source

All Articles