function not_found_error
Flask error handler that renders a custom error page when a 404 (Page Not Found) error occurs.
/tf/active/vicechatdev/full_smartstat/app.py
1794 - 1795
simple
Purpose
This function serves as a Flask error handler specifically for HTTP 404 errors. When a user attempts to access a non-existent route in the Flask application, this handler intercepts the error and returns a user-friendly error page instead of the default Flask 404 page. It provides a consistent error experience across the application by using a custom template.
Source Code
def not_found_error(error):
return render_template('error.html', error="Page not found"), 404
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
error |
- | - | positional_or_keyword |
Parameter Details
error: The error object automatically passed by Flask's error handling mechanism when a 404 error occurs. Contains information about the error that triggered this handler, though it is not used in the function body.
Return Value
Returns a tuple containing two elements: (1) the rendered HTML template 'error.html' with an error message 'Page not found' passed as a template variable, and (2) the HTTP status code 404. Flask uses this tuple to construct the HTTP response sent to the client.
Dependencies
flask
Required Imports
from flask import render_template
Usage Example
from flask import Flask, render_template
app = Flask(__name__)
@app.errorhandler(404)
def not_found_error(error):
return render_template('error.html', error="Page not found"), 404
# When a user navigates to a non-existent route like '/nonexistent'
# Flask will automatically call this handler and display the error page
if __name__ == '__main__':
app.run()
Best Practices
- Ensure the 'error.html' template exists and is properly designed to handle error messages
- Consider logging the 404 error for monitoring purposes before returning the response
- The error parameter could be used to extract additional context about the failed request if needed
- Maintain consistent error handling patterns across all error handlers (404, 500, etc.)
- Test that the error handler works correctly by attempting to access non-existent routes
- Consider adding user-friendly navigation links in the error template to help users return to valid pages
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function not_found 98.3% similar
-
function not_found_v1 87.2% similar
-
function not_found_v2 82.0% similar
-
function internal_error_v1 67.5% similar
-
function internal_error_v2 65.2% similar