function internal_error_v2
Flask error handler that catches internal server errors (HTTP 500), logs them, and renders a user-friendly error page.
/tf/active/vicechatdev/vice_ai/app.py
1701 - 1703
simple
Purpose
This function serves as a centralized error handler for all unhandled exceptions in a Flask application. When a 500 Internal Server Error occurs, it logs the error details for debugging purposes and returns a standardized error page to the user, preventing exposure of sensitive stack traces or system information.
Source Code
def internal_error(error):
logger.error(f"Internal error: {error}")
return render_template('error.html', error='Internal server error'), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
error |
- | - | positional_or_keyword |
Parameter Details
error: The exception or error object that triggered the 500 error. This can be any Python exception that was not caught by the application code. The error object is logged for debugging and can contain the exception message, type, and traceback information.
Return Value
Returns a tuple containing: (1) the rendered HTML template 'error.html' with an 'error' variable set to 'Internal server error', and (2) the HTTP status code 500. This tuple is Flask's standard format for returning both content and status code.
Dependencies
flasklogging
Required Imports
from flask import Flask
from flask import render_template
import logging
Usage Example
from flask import Flask, render_template
import logging
app = Flask(__name__)
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.ERROR)
@app.errorhandler(500)
def internal_error(error):
logger.error(f"Internal error: {error}")
return render_template('error.html', error='Internal server error'), 500
@app.route('/test-error')
def test_error():
# This will trigger the error handler
raise Exception('Test error')
if __name__ == '__main__':
app.run(debug=False)
Best Practices
- Always register this handler using the @app.errorhandler(500) decorator to ensure it catches all unhandled exceptions
- Ensure the logger is properly configured before the Flask app starts to capture error logs
- The error.html template should be generic and not expose sensitive system information to users
- Consider adding more detailed error logging (like traceback) in development mode while keeping user-facing messages generic
- In production, ensure DEBUG mode is disabled so this handler catches errors instead of Flask's debug page
- Consider logging additional context like request URL, user session info, or timestamp for better debugging
- The error parameter should not be directly rendered to users as it may contain sensitive information
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function internal_error_v1 96.4% similar
-
function internal_error 93.2% similar
-
function handle_exception 80.5% similar
-
function not_found 66.5% similar
-
function not_found_error 65.2% similar