eriophora
eriophora

Reputation: 1049

Give Flask error handler access to request

I'm trying to make a custom error page in Flask, and I'd like to give the error handler access to the request that generated the API call that caused the error so that the error page it returns can change depend on the circumstances. For instance, say there are two endpoints:

(1) @app.route('/get_item')

(2) @app.route('/submit_item')

If an error occurs during a call to get_item, I want to display a certain error page ("Sorry, an error occurred...") however, if an error occurs during a call to submit_item, I want it to say something more informative, like:

"An error occured! Please contact us.

Your user id: request.json['userid']

Your submission id: request.json['submission']"

Is it possible to allow the error handler to have access to this, or do I just have to wrap the whole of submit_item in try/except statements?

Upvotes: 6

Views: 3642

Answers (2)

mguijarr
mguijarr

Reputation: 7900

You can use the request context in the error handler function, something along those lines:

from flask import request

def exception_handler(*args):
    if request.url.endswith('submit_item'):
       return "MyMoreDescriptiveErrorMessage", 500
    else:
       return "Something wrong happened", 500

Upvotes: 7

Suever
Suever

Reputation: 65430

I would probably create a custom exception and specify an error handler for it similar to this example.

class CustomException(Exception):

    def __init__(self, message=None, status_code=None, payload=None):
        Exception.__init__(self)

        if message is None:
            message = "Sorry, an error occurred..."

        self.message = message

        if status_code is not None:
            self.status_code = status_code
        self.payload = payload


@app.errorhandler(CustomException)
def handle_custom(error):
    response = render_template('error.html', message=error.message)
    response.status_code = error.status_code
    return response

@app.route('/submit_item')
def submit_item():
     message = "An error occured! Userid: %(userid)d, submission: %(submission_id)d"
     message = message % (request.json)

     raise CustomException(message)

Upvotes: 1

Related Questions