Thursday, 15 July 2010

google app engine - How to JSON format an HTTP error response in webapp2 -


I am using webapp2 for development in App Engine. What I want to do to send a custom JSON formatted response in case of an error, for example when the length of request is large, to respond to a Threshold, HTTP 400 and response body

  {'Error': 'InvalidMessageLength'}   

In WebApp2, there are some exceptions to the option of assigning an error handler. For example:

  app.error_handlers [400] = handle_error_400   

where handle_error_400 is the following:

  def handle_error_400 (Request) The above code is executed.  

How dynamically different response formats (HTML and JSON) are based on the above setup? That is, how is it possible to call different versions of the handle_error_400 function?

Here is a fully working example which is the same error handler for all types of errors And if your URL starts with / json then a response code / JSN (what kind of feedback should you give, to decide if you want to < Code> request how to make good use of the object, use its own imagery):

  import Webapp2 import json def handle_error (request, feedback, exception): if request.path.startswith ('/ json'): response.headers.add_header ('content-type', 'app / jason') result = {'status' : 'Error', 'Status_code': exception.code, 'error_message': exception.explanation,} response.write (json.dumps (result)) Other: response.write (exception) response.set_status (exception.code) app = Webapp2WSGIApplication () app.error_handlers [404] = handle_error app.error_handlers [400] = Handler Dior   

In the above example, you can easily test different behaviors through the following URLs: Which is a 404 Test that is the easiest error:

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

No comments:

Post a Comment