Skip to content

Instantly share code, notes, and snippets.

@exhuma
Created February 2, 2017 09:04
Show Gist options
  • Save exhuma/d31d4a74692db9c31157f9f864a9046e to your computer and use it in GitHub Desktop.
Save exhuma/d31d4a74692db9c31157f9f864a9046e to your computer and use it in GitHub Desktop.
flask-exception-problem

I've tried upgrading from Flask 0.10.1 to 0.12 today and ran into a little issue:

I am maintaining a larger application which also provides a JSON API on top of a subset of it's functionalities via Flask. In order to make error handling consistent I defined a simple mixin class:

class RestExceptionMixin(object):
    """
    Mixin for exceptions which can be used in a REST API.
    """
    status_code = 400

    def to_dict(self):
        output = {}
        if hasattr(self, 'message'):
            output['messages'] = [self.message]
        else:
            output['messages'] = [str(self)]
        return output

This allowed me to write the following exeption handler (in Flask 0.10.1):

@HANDLER.app_errorhandler(RestExceptionMixin)
@supported_mediatypes(response=[mt.OLD_ERROR, mt.ERROR])
@logstash(__name__, 'unknown')
def rest_exception(request_type, response_type, error):
    """
    Handles any exception which inherits from
    :py:class:`~ipbase.exc.RestExceptionMixin` (most exceptions from
    :py:mod:`ipbase.exc`).
    """
    LOG.warning('Unhandled RestException intercepted!', exc_info=True)
    if response_type == mt.ERROR:
        response = make_error_response('Unknown error', str(error),
                                       error.status_code, safe=False)
    elif response_type == mt.OLD_ERROR:
        response = jsonify(error.to_dict())
        response.status_code = error.status_code
        response.content_type = response_type
    return response

This allows me to simply add the mixin class to an existing exception and all those exceptions become automatically handled by Flask. Now in Flask 0.12 this no longer works as Flask enforces the argument to "error_handler" to be a subclass from Exception. Unfortunately, I cannot make RestExceptionMixin a subclass of Exception as that would introduce a diamond problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment