What is the difference between abort(400)
and returning a response with a 400 status? Is using return bad form for errors?
abort(400, "some error message")
# or
return {'message': "some error message"}, 400
Flask comes with a handy abort() function that aborts a request with an HTTP error code early. It will also provide a plain black and white error page for you with a basic description, but nothing fancy. Depending on the error code it is less or more likely for the user to actually see such an error.
To achieve what you want to do, you have to pass a Response object to the abort method. One of the reasons you'll create a Response object instead of allowing render_template or abort do it for you is when you need to add a custom header to a response or change the default headers that abort adds to the response.
You could use abort(http_code) to return an appropriate http code to the client or just raise a non-http exception. And use @app. errorhandler() decorator to provide a custom handler for http errors and arbitrary exceptions. You could also use an ordinary try/except block where you are ready to handle an exception.
Create a function whose only argument is the HTTP error status code, make it return a flask. Response instance, and decorate it with @app. errorhandler. You can then use abort(401) to your heart's content.
abort
raises an error, which an error handler will convert to a response. return
returns a response, error handlers don't trigger. It's up to how you want your application to flow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With