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
Lipis source share