Flask Error Handling - BKJackson/BKJackson_Wiki GitHub Wiki

Make a function that returns json for an error (instead of the usual HTML)

From PYCON UK 2017: Recipes for Productionising Data Science APIs - min 9:26

from wekzeug.exceptions import HTTPException  

def json_errorhandler(exception):  
  if isinstance(exception, HTTPException):  
    message = exception.description  
    code = exception.code  
  else:  
    message = 'Internal server error'  
    code = 500  
  response = jsonify({  
    'message': message,  
    'error': True })
  reponse.status_code = code
  return response  

Then register the function as the error handler:

from werkzeug.exceptions import default_exceptions  

for code in default_exceptions.keys():  
  app.register_error_handler(code, json_errorhandler)  

Try testing this with GET /does-not-exist, should return 404 NOT FOUND.
Try testing this with POST /foo, should return 405 METHOD NOT ALLOWED.

Flask Error Handling Docs

Application Error Handling - Applications fail, servers fail. Sooner or later you will see an exception in production. Even if your code is 100% correct, you will still see exceptions from time to time. Why? Because everything else involved will fail. Here are some situations where perfectly fine code can lead to server errors.