Catching custom exceptions raised in Flask API. All exceptions raised end up in 500 Error [duplicate] Catching custom exceptions raised in Flask API. All exceptions raised end up in 500 Error [duplicate] flask flask

Catching custom exceptions raised in Flask API. All exceptions raised end up in 500 Error [duplicate]


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)def exception_handler(e):    return jsonify({'message': e._message().split('"')[2].strip()}), 400# Custom Error handler# Duplicated column value@app.errorhandler(APIException)def exception_handler(e):    return jsonify({'message': e.description}), 400

And same usage in view

@app.route('/')def index():    if something_wrong():        raise APIExceptionclass ARouteAPI():    def post(data):        if not 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>}}}