0
votes

I'm going through the RESTful web services chapter of the Flask web development book by Miguel Grinberg and he mentions that errors can be generated by Flask on its own or explicitly by the web service.

For errors generated by Flask, he uses a error handler like the following:

@main.app_errorhandler(404)
def page_not_found(e):
    if request.accept mimetypes.accept_json and \
            not request.accept_mimetypes.accept_html:
        response = jsonify({'error': 'not found'})
        response.status_code = 404
        return response
     return render_template('404.html'), 404

While errors generated by the web service, have no error handler:

def forbidden(message):
    response = jsonify({'error': 'forbidden', 'message': message})
    response.status_code = 403
    return response

I don't really understand the difference between a flask generated error vs a web service generated error.

1

1 Answers

0
votes

The first is an example of how to make a custom handler for an error that Flask will raise. For example, it will raise a 404 error with a default "not found" message if it doesn't recognize the path. The custom handler allows you to still return the 404 error, but with your own, nicer looking response instead.

The second is an example of how to change the code for your response, without handling a previously raised error. In this example, you would probably return forbidden() from another view if the user doesn't have permission. The response would have a 403 code, which your frontend would know how to handle.