Skip to content Skip to sidebar Skip to footer

Catching Custom Exceptions Raised In Flask Api. All Exceptions Raised End Up In 500 Error

I want to be able to raise validation and other exceptions in my API and catch them in a wrapped view that will return the error message as JSON. I thought I could use something l

Solution 1:

I used app.errorhandler for handling errors in flask. (No matter whether it is custom error, or std error)

# IntegrityError Error handler@app.errorhandler(IntegrityError)defexception_handler(e):
    return jsonify({'message': e._message().split('"')[2].strip()}), 400# Custom Error handler# Duplicated column value@app.errorhandler(APIException)defexception_handler(e):
    return jsonify({'message': e.description}), 400

And same usage in view

@app.route('/')defindex():
    if something_wrong():
        raise APIException

classARouteAPI():
    defpost(data):
        ifnot data.something:
            raise APIException("Invalid data error")

Don't forget to make sure your handlers are added by flask app

>>> print(app.error_handler_spec)
{None: {None: {<class'sqlalchemy.exc.IntegrityError'>: <function exception_handler at 0x10ae24158>,
               <class'app.error.exc.DuplicatedValueError'>: <function exception_handler at 0x10ae54268>,
               <class'app.error.exc.WrongSelectionError'>: <function exception_handler at 0x10ae542f0>},
        404: {<class'werkzeug.exceptions.NotFound'>: <function exception_handler at 0x10a53c7b8>}}}

Post a Comment for "Catching Custom Exceptions Raised In Flask Api. All Exceptions Raised End Up In 500 Error"