Skip to content
Myr

apierrors.rst

This file

Path

docs/patterns/apierrors.rst

63 lines · 2.1 KiB

Last changed by

Not known.

History of this file

Take it

1Implementing API Exceptions2===========================34It's very common to implement RESTful APIs on top of Flask.  One of the5first things that developers run into is the realization that the builtin6exceptions are not expressive enough for APIs and that the content type of7:mimetype:`text/html` they are emitting is not very useful for API consumers.89The better solution than using ``abort`` to signal errors for invalid API10usage is to implement your own exception type and install an error handler11for it that produces the errors in the format the user is expecting.1213Simple Exception Class14----------------------1516The basic idea is to introduce a new exception that can take a proper17human readable message, a status code for the error and some optional18payload to give more context for the error.1920This is a simple example::2122    from flask import jsonify2324    class InvalidUsage(Exception):25        status_code = 4002627        def __init__(self, message, status_code=None, payload=None):28            Exception.__init__(self)29            self.message = message30            if status_code is not None:31                self.status_code = status_code32            self.payload = payload3334        def to_dict(self):35            rv = dict(self.payload or ())36            rv['message'] = self.message37            return rv3839A view can now raise that exception with an error message.  Additionally40some extra payload can be provided as a dictionary through the `payload`41parameter.4243Registering an Error Handler44----------------------------4546At that point views can raise that error, but it would immediately result47in an internal server error.  The reason for this is that there is no48handler registered for this error class.  That however is easy to add::4950    @app.errorhandler(InvalidUsage)51    def handle_invalid_usage(error):52        response = jsonify(error.to_dict())53        response.status_code = error.status_code54        return response5556Usage in Views57--------------5859Here is how a view can use that functionality::6061    @app.route('/foo')62    def get_foo():63        raise InvalidUsage('This view is gone', status_code=410)