Last active
March 6, 2020 16:32
-
-
Save paparaka/b303b1a15907ae30ed0145053876221f to your computer and use it in GitHub Desktop.
Flask.Exception.Chaining
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
An example Flask app that uses Exceptions to return errors to clients | |
""" | |
from flask import Flask, jsonify | |
app = Flask(__name__) | |
class APIError(Exception): | |
"""All custom API Exceptions""" | |
pass | |
class APIAuthError(APIError): | |
"""Custom Authentication Error Class.""" | |
code = 403 | |
description = "Authentication Error" | |
@app.errorhandler(APIError) | |
def handle_exception(err): | |
"""Return custom JSON when APIError or its children are raised""" | |
response = {"error": err.description, "message": ""} | |
if len(err.args) > 0: | |
response["message"] = err.args[0] | |
# Add some logging so that we can monitor different types of errors | |
app.logger.error(f"{err.description}: {response["message"]}") | |
return jsonify(response), err.code | |
@app.errorhandler(500) | |
def handle_exception(err): | |
"""Return JSON instead of HTML for any other server error""" | |
app.logger.error(f"Unknown Exception: {str(err)}") | |
app.logger.debug(''.join(traceback.format_exception(etype=type(err), value=err, tb=err.__traceback__))) | |
response = {"error": "Sorry, that error is on us, please contact support if this wasn't an accident"} | |
return jsonify(response), 500 | |
@app.route("/") | |
def hello(): | |
return jsonify("Hello World!"), 200 | |
@app.route("/BadBoy") | |
def fail(): | |
raise Exception('Someone has been naughty') | |
def check_user_exists(username): | |
""" Some function that returns True if username is in the DB""" | |
return True | |
def check_password_is_correct(username, password): | |
""" Some function that returns True if password for username is correct """ | |
return True | |
@router.route("/user/login", methods=['POST']) | |
def user_login(): | |
if "email" not in request.data: | |
raise APIAuthError('Missing email value') | |
if "password" not in request.data: | |
raise APIAuthError('Missing password value') | |
if check_user_exists(request.data["email"]) and check_password_is_correct(request.data["email"], request.data["password"]): | |
return "Success", 200 | |
else: | |
raise APIAuthError('Incorrect Credentials') | |
if __name__ == '__main__': | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment