flask @app.errorhandler
时间: 2024-01-15 22:05:43 浏览: 75
Request的中断和ErrorHandler实例解析
@app.errorhandler is a decorator in Flask that allows you to handle specific error codes or exceptions in your application. It is used to define custom error handling functions.
For example, if you want to handle a 404 error (page not found), you can use the @app.errorhandler(404) decorator before your error handling function. Here's an example:
```python
from flask import Flask
app = Flask(__name__)
@app.errorhandler(404)
def page_not_found(error):
return "Page not found", 404
if __name__ == '__main__':
app.run()
```
In this example, whenever a 404 error occurs, the `page_not_found` function will be called, and it will return the message "Page not found" with a status code of 404.
You can also use @app.errorhandler to handle specific exception types. For example, if you want to handle a specific exception like ValueError, you can do:
```python
@app.errorhandler(ValueError)
def handle_value_error(error):
return "Invalid value", 400
```
In this case, whenever a ValueError occurs, the `handle_value_error` function will be called, and it will return the message "Invalid value" with a status code of 400.
By using @app.errorhandler, you can customize the error handling behavior of your Flask application.
阅读全文