function not_found_v1
Flask error handler that returns a JSON response with a 404 status code when a requested resource is not found.
/tf/active/vicechatdev/docchat/app.py
1519 - 1520
simple
Purpose
This function serves as a custom error handler for Flask applications to provide consistent JSON-formatted error responses when users attempt to access non-existent routes or resources. It's registered as an error handler for HTTP 404 errors using the @app.errorhandler(404) decorator, ensuring all 404 errors return a standardized JSON response instead of Flask's default HTML error page.
Source Code
def not_found(error):
return jsonify({'error': 'Not found'}), 404
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
error |
- | - | positional_or_keyword |
Parameter Details
error: The error object automatically passed by Flask when a 404 error occurs. This parameter contains information about the error but is not used in the function body. It's required by Flask's error handler signature.
Return Value
Returns a tuple containing: (1) a JSON object with structure {'error': 'Not found'} created by Flask's jsonify() function, and (2) the HTTP status code 404. Flask automatically converts this tuple into a proper HTTP response with JSON content-type headers.
Dependencies
flask
Required Imports
from flask import Flask
from flask import jsonify
Usage Example
from flask import Flask, jsonify
app = Flask(__name__)
@app.errorhandler(404)
def not_found(error):
return jsonify({'error': 'Not found'}), 404
@app.route('/')
def home():
return 'Home Page'
if __name__ == '__main__':
app.run()
# When accessing a non-existent route like '/nonexistent':
# Response: {'error': 'Not found'} with status code 404
Best Practices
- This error handler should be registered after all route definitions to ensure it catches all 404 errors
- Consider adding more detailed error information in production environments, such as timestamp or request path
- For APIs, ensure all error responses follow a consistent JSON structure across different error types
- The error parameter should be kept in the signature even if unused, as Flask requires it for error handlers
- Consider logging the error for debugging purposes before returning the response
- This pattern works well for RESTful APIs where JSON responses are expected for all endpoints
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function not_found_v2 94.1% similar
-
function not_found 87.4% similar
-
function not_found_error 87.2% similar
-
function handle_exception 67.5% similar
-
function internal_error 64.3% similar