I have made an API app using flask, that takes a number(decimal) as input and returns some string. This app breaks if I send a string and works fine after re-starting it. I don\
When looking into the documents we can find this behaviour:
handle_exception(e)
Handle an exception that did not have an error handler associated with it, or that was raised from an error handler. This always causes a 500 InternalServerError.
Always sends the got_request_exception signal.
If propagate_exceptions is True, such as in debug mode, the error will be re-raised so that the debugger can display it. Otherwise, the original exception is logged, and an InternalServerError is returned.
If an error handler is registered for InternalServerError or 500, it will be used. For consistency, the handler will always receive the InternalServerError. The original unhandled exception is available as e.original_exception.
A way to catch this errors and do something with it could be this:
@app.errorhandler(Exception)
def handle_exception(e):
# pass through HTTP errors
if isinstance(e, HTTPException):
return e
# now you're handling non-HTTP exceptions only
return render_template("500_generic.html", e=e), 500
Source and extra documentation if needed you can find here:
Flask pallets projects
You can make a decorator that is a global exception handler:
import traceback
from flask import current_app
def set_global_exception_handler(app):
@app.errorhandler(Exception)
def unhandled_exception(e):
response = dict()
error_message = traceback.format_exc()
app.logger.error("Caught Exception: {}".format(error_message)) #or whatever logger you use
response["errorMessage"] = error_message
return response, 500
And wherever you create your app instance, you need to do this:
from xxx.xxx.decorators import set_global_exception_handler
app = Flask(__name__)
set_global_exception_handler(app)
This will handle all exceptions generated in your application along with whatever else you need to do to handle them. Hope this helps.
You need to trigger a return with an error message, if whatever the user submits can't be expressed as an integer.
The following should work for submissions like 3
and '3'
# now the processing part
try:
number = int(json_data['number'])
except ValueError:
return jsonify(['Invalid submission'])
# Number is now type integer
if number < 2:
return jsonify(["the number is less than two"])
else:
return jsonify(["the number is not less than two"])