2

For returning a 400/500 response to clients in a flask webapp, I've seen the following conventions:

Abort

import flask
def index(arg):
    return flask.abort("Invalid request", 400)

Tuple

def index(arg):
    return ("Invalid request", 400)

Response

import flask
def index(arg):
    return flask.Response("Invalid request", 400)

What are the difference and when would one be preferred?

Related question

Coming from Java/Spring, I am used to defining a custom exception with a status code associated with it and then anytime the application throws that exception, a response with that status code is automatically returned to the user (instead of having to explicitly catch it and return a response as shown above). Is this possible in flask? This is my little wrapped attempt

from flask import Response

class FooException(Exception):
    """ Binds optional status code and encapsulates returing Response when error is caught """
    def __init__(self, *args, **kwargs):
        code = kwargs.pop('code', 400)
        Exception.__init__(self)
        self.code = code

    def as_http_error(self):
        return Response(str(self), self.code)

Then to use

try:
    something()
catch FooException as ex:
    return ex.as_http_error()
Adam Hughes
  • 14,601
  • 12
  • 83
  • 122

1 Answers1

7

The best practice is to create your custom exception classes and then registering with Flask app through error handler decorator. You can raise a custom exception from business logic and then allow the Flask Error Handler to handle any of custom defined exceptions. (Similar way it's done in Spring as well.)

You can use the decorator like below and register your custom exception.

@app.errorhandler(FooException)
def handle_foo_exception(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

You can read more about it here Implementing API Exceptions

Saurabh
  • 528
  • 2
  • 8