How can I implement my own error handler for all HTTP errors in Flask?

In my Flask application, I can easily expand the list of errors handled by one custom error handler by adding decorators errorhandlerfor each error code, as in

@application.errorhandler(404)
@application.errorhandler(401)
@application.errorhandler(500)
def http_error_handler(error):
    return flask.render_template('error.html', error=error), error.code

However, this approach requires an explicit decorator for each error code. Is there any way to decorate my (one) function http_error_handlerso that it handles all HTTP errors?

+4
source share
3 answers

, http, , application.error_handler_spec, , :

def http_error_handler(error):
    return flask.render_template('error.html', error=error), error.code

for error in (401, 404, 500): # or with other http code you consider as error
    application.error_handler_spec[None][error] = http_error_handler

, , , , - . , .

+3

errorhandler , , . ,

@application.errorhandler(HTTPException)
def http_error_handler(error):

HTTP ( HTTP)

@application.errorhandler(Exception)
def http_error_handler(error):

: , TRAP_HTTP_EXCEPTIONS, (, app.config['TRAP_HTTP_EXCEPTIONS']=True).

() , , HTTPException, , errorhandler(n), n - HTTP; , HTTPException , errorhandler(c), c - .

,

app.config['TRAP_HTTP_EXCEPTIONS']=True

@application.errorhandler(Exception)
def http_error_handler(error):

, .

HTTPException HTTP (. ), 'TRAP_HTTP_EXCEPTIONS' , , .

, :

app.config['TRAP_HTTP_EXCEPTIONS']=True

@app.errorhandler(Exception)
def handle_error(e):
    try:
        if e.code < 400:
            return flask.Response.force_type(e, flask.request.environ)
        elif e.code == 404:
            return make_error_page("Page Not Found", "The page you're looking for was not found"), 404
        raise e
    except:
        return make_error_page("Error", "Something went wrong"), 500

, , , , , HTTP, . if e.code < 400 .. ( 500s, , )

+6

:

@app.errorhandler(HTTPException)
def _handle_http_exception(e):
    return make_response(render_template("errors/http_exception.html", code=e.code, description=e.description), e.code)

But the change HTTPExceptionto the real one, for example NotFound, worked. Do not ask me why, I did not find the answer.

So, I found an alternative solution that works very well:

from werkzeug.exceptions import default_exceptions

def _handle_http_exception(e):
    return make_response(render_template("errors/http_exception.html", code=e.code, description=e.description), e.code)

for code in default_exceptions:
    app.errorhandler(code)(_handle_http_exception)

(Found on Github )

+2
source

Source: https://habr.com/ru/post/1569843/


All Articles