Skip to content Skip to sidebar Skip to footer

How To Catch All Exceptions Raised In Flask_restful App

I do have simple restful app with Flask-Restful from flask import Flask from flask_restful import Api app = Flask(__name__) ... api = Api(app) api.add_resource(ContactList, '/con

Solution 1:

There is a Flask-Restful built-in tool for handling exceptions, you can pass a dictionary of exception classes and response fields to Api constructor:

api = Api(app, errors={
    'Exception': {
        'status': 400,
        'message': 'bad_request',
        'some_description': 'Something wrong with request'
    }
})

Status is 500 by default, all other field are just turned to JSON and sent in response.

There is a major downside: you cannot use exception text as error message. There is an open issue for it.

Solution 2:

Sentry is a great tool for catching exceptions across different platforms and frameworks {Including Python, Django and Flask}. This example give pointers on you can integrate it with your Flask application.

I've used it in production, the feature I liked the most is that it captures context of the error, including Operating System, Browser Version etc along with other information.

Post a Comment for "How To Catch All Exceptions Raised In Flask_restful App"