flask-state icon indicating copy to clipboard operation
flask-state copied to clipboard

Using custom exception with app error handler

Open FesonX opened this issue 4 years ago • 0 comments

Flask mentions Implementing API Exceptions in docs, which MAY be better than what we used in current project.

from flask import jsonify

class InvalidUsage(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        Exception.__init__(self)
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv

@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

@app.route('/foo')
def get_foo():
    """**Just raise and don't need more try-catch code!**"""
    raise InvalidUsage('This view is gone', status_code=410)

FesonX avatar Jul 27 '21 00:07 FesonX