Skip to main content

Flask REST API error handling best practices?

I am writing a Flask REST API. When a request is received, the API calls functions to interact with a database.

Currently, i am catching errors with try: except: statements and then returning custom http responses based off of the raised exception.

However, i just learned of the @errorhandler decorator. Rather than writing repeated try: except: statements, should i instead write a number of custom error classes, and then assign each class to an @errorhandler. Then within my code, remove the try: except: statements and raise the custom errors when neccessary?

Current code:

from flask import Flask, jsonify, request

app = Flask(__name__)


@app.route('/example', methods=['POST'])
    def create_user():
        try:
            data = request.get_json()
            # Call example function to interact with database
            response = db_example(data=data)
            return response
        except (KeyError, Exception):
            response = jsonify({"error": "example error message"})
            response.status_code = 400
            return response
        
# Example function to interact with database
def db_example(data):
    try:
        # Connect to database
        # Execute query
        # Handle result data etc...
        response = jsonify({"success": "example success message"})
        response.status_code = 200
        return response
    except (KeyError, Exception):
        # Unexpected error raised
        response = jsonify({"error": "example error message"})
        response.status_code = 500
        return response

Or is the below code considered better practice?

from flask import Flask, jsonify, request

app = Flask(__name__)

# Class for custom errors
class APIError(Exception):
    """ ALL CUSTOM EXCEPTIONS """
    code = 400
    description = "Invalid data"


@app.errorhandler(APIError)
    def handle_exception(err):
        response = jsonify({"error": err.description})
        response.status_code = err.code
        return response


@app.route('/example', methods=['POST'])
def create_user():
    data = request.get_json()
    # Call example function to interact with database
    response = db_example(data=data)
    return response

# Example function to interact with database
def db_example(data):
    success = False
    # Connect to database
    # Execute query
    # Handle result data etc...
    if success
        response = jsonify({"success": "example success message"})
        response.status_code = 200
    else:
        raise APIError



source https://stackoverflow.com/questions/75700666/flask-rest-api-error-handling-best-practices

Comments