[Python] Proper error handling using FLASK-RESTful

Discussão em 'Python' iniciado por Stack, Setembro 17, 2024.

  1. Stack

    Stack Membro Participativo

    I have a FLASK API, for which I have used the FLASK-RESTful package:

    main.py

    class MyEndpoint(Resource):
    def post(self):
    result = my_function()
    return result


    my_function is a function imported from another file and it can raise all type of exceptions, including all the python Build-in exceptions.. My question is should I be creating a error_handling.py separate file or what is the convention to handle my exceptions properly?

    I don't want to end up with something like this:

    def handle_error(error):
    # Base structure for JSON error responses
    error_response = {
    "error_type": type(error).__name__,
    "message": str(error)
    }

    ### 1. Flask/HTTP-Specific Errors ###
    if isinstance(error, HTTPException):
    # This covers HTTP-related errors (404, 400, etc.)
    return jsonify({
    "error_type": error.name,
    "message": error.description
    }), error.code

    ### 2. Python Built-in Exceptions ###
    elif isinstance(error, ValueError):
    error_response["message"] = "Invalid value provided."
    return jsonify(error_response), 400 # Bad Request

    elif isinstance(error, TypeError):
    error_response["message"] = "Type mismatch error."
    return jsonify(error_response), 400 # Bad Request

    elif isinstance(error, KeyError):
    error_response["message"] = "Missing required key."
    return jsonify(error_response), 400 # Bad Request

    elif isinstance(error, IndexError):
    error_response["message"] = "Index out of range."
    return jsonify(error_response), 400 # Bad Request

    elif isinstance(error, AttributeError):
    error_response["message"] = "Attribute missing or invalid."
    return jsonify(error_response), 400 # Bad Request

    elif isinstance(error, UnboundLocalError):
    error_response["message"] = "Unbound local variable."
    return jsonify(error_response), 500 # Internal Server Error

    elif isinstance(error, ZeroDivisionError):
    error_response["message"] = "Division by zero error."
    return jsonify(error_response), 400 # Bad Request

    elif isinstance(error, FileNotFoundError):
    error_response["message"] = "File not found."
    return jsonify(error_response), 404 # Not Found

    Continue reading...

Compartilhe esta Página