Catching a 500 server error in Flask

后端 未结 6 1284
-上瘾入骨i
-上瘾入骨i 2021-02-01 12:41

I love Flask\'s error catching. It\'s beautifully simple:

@app.errorhandler(404)
def pageNotFound(error):
    return \"page not found\"

works

6条回答
  •  梦谈多话
    2021-02-01 13:39

    It works fine in my side:

    from flask import Flask ,url_for,render_template,request,abort
    from  werkzeug.debug import get_current_traceback
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        try:
            raise Exception("Can't connect to database")
        except Exception,e:
            track= get_current_traceback(skip=1, show_hidden_frames=True,
                ignore_system_exceptions=False)
            track.log()
            abort(500)
        return "index"
    
    @app.errorhandler(500)
    def internal_error(error):
    
        return "500 error"
    
    @app.errorhandler(404)
    def not_found(error):
        return "404 error",404
    
    if __name__== "__main__":
        app.run(debug=True)
    

    Flask will not set the error code for you, so make sure to also provide the HTTP status code when returning a response.

提交回复
热议问题