function not_found
Flask error handler function that renders a custom error page when a 404 (Page Not Found) error occurs.
/tf/active/vicechatdev/vice_ai/app.py
1697 - 1698
simple
Purpose
This function serves as a centralized error handler for 404 HTTP errors in a Flask web application. When a user attempts to access a non-existent route or resource, this handler intercepts the error and returns a user-friendly error page instead of the default Flask 404 page. It uses the Flask template rendering system to display a custom error.html template with an appropriate error message.
Source Code
def not_found(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 passed by Flask's error handling mechanism. This contains information about the 404 error that occurred, including the request details and error context. The parameter is required by Flask's errorhandler decorator but is not directly used in the function body.
Return Value
Returns a tuple containing two elements: (1) the rendered HTML template as a string generated from 'error.html' with the error message 'Page not found' passed as a template variable, and (2) the HTTP status code 404. This tuple format is Flask's standard way of returning both content and status code from a view function.
Dependencies
flask
Required Imports
from flask import Flask
from flask import render_template
Usage Example
from flask import Flask, render_template
app = Flask(__name__)
@app.errorhandler(404)
def not_found(error):
return render_template('error.html', error='Page not found'), 404
@app.route('/')
def home():
return 'Home Page'
if __name__ == '__main__':
app.run(debug=True)
# When a user navigates to a non-existent route like '/nonexistent',
# the not_found function will be automatically called and render the error page
Best Practices
- Ensure the error.html template exists and is properly designed to handle error messages gracefully
- The error parameter should be kept in the function signature even if unused, as Flask's errorhandler decorator requires it
- Consider logging the error details for debugging purposes before rendering the template
- The error.html template should be user-friendly and provide helpful navigation options (e.g., link back to home page)
- Always return the appropriate HTTP status code (404) along with the rendered template
- Consider adding additional error handlers for other HTTP error codes (500, 403, etc.) following the same pattern
- Avoid exposing sensitive application details in the error message displayed to users
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function not_found_error 98.3% similar
-
function not_found_v1 87.4% similar
-
function not_found_v2 82.0% similar
-
function internal_error_v1 68.7% similar
-
function internal_error_v2 66.5% similar