YouTip LogoYouTip

Flask Error

Flask provides a flexible error handling mechanism that can capture and handle various errors in the application. Good error handling is not just about "no bugs", but also providing a friendly experience when bugs occur. This chapter introduces how to customize error pages and manage logs in Flask. * * * ## Custom Error Pages By default, Flask displays a simple black background white text page for errors like 404. You can use the @app.errorhandler decorator to customize error pages for specific HTTP status codes: ## Example from flask import Flask, render_template app = Flask( __name__ ) # Handle 404 error - page not found @app.errorhandler(404) def page_not_found(error): # Note: Must explicitly return status code 404 return render_template("404.html"),404 # Handle 500 error - internal server error @app.errorhandler(500) def internal_error(error): return render_template("500.html"),500 # Handle 403 error - forbidden access @app.errorhandler(403) def forbidden(error): return render_template("403.html"),403 The corresponding 404 template: ## Example 404 - Page Not Found body { text-align: center; padding-top: 60px; font-family: Arial; } h1 { font-size: 72px; color: #e74c3c; margin: 0; } p { color: #666; font-size: 18px; } a { color: #3498db; }

404

Sorry, the page you are visiting does not exist.

Return to Homepage

> In functions decorated with errorhandler, the return must explicitly include the status code. If you don't write , 404, Flask will return status code 200 by default, and browsers and search engines will not recognize this as an error page. * * * ## Exception Class Registration In addition to status codes, @app.errorhandler can also register exception classes directly: ## Example from werkzeug.exceptions import HTTPException @app.errorhandler(HTTPException) def handle_http_exception(error): """Handle all HTTP exceptions uniformly (such as 400, 401, 403, 404, etc.)""" return f"""

HTTP Error {error.code}

{error.description}

Return to TUTORIAL Homepage

""", error.code * * * ## Using abort to Trigger Errors In your view functions, use abort() to actively trigger HTTP errors: ## Example from flask import abort # Simulate an article database articles ={ 1: {"title": "Flask Getting Started Tutorial"}, 2: {"title": "Python Basics"}, } @app.get("/article/") def view_article(article_id): article = articles.get(article_id) if article is None: # Article does not exist, return 404 # description parameter will be passed to errorhandler abort(404, description=f"Article ID {article_id} does not exist") return f"

{article['title']}

" @app.get("/admin") def admin_panel(): # Users without admin permission access the admin backend abort(403, description="You do not have administrator permissions") * * * ## Logging Flask uses Python's standard library logging module, and you can record logs through app.logger. Logs are essential for troubleshooting - don't just use print(), logs provide richer context and better control. ## Example from flask import Flask, request app = Flask( __name__ ) @app.route("/") def index(): # Different levels of logs app.logger.debug("Accessing homepage")# Debug info, usually not output in production app.logger.info("User from IP: %s", request.remote_addr)# General info app.logger.warning("Abnormal access pattern detected")# Warning: needs attention but doesn't affect operation app.logger.error("Database connection failed")# Error: functionality affected app.logger.critical("Insufficient disk space, service will stop soon")# Critical: service may stop return"OK" Log levels (from low to high): | Level | Use Case | | --- | --- | | DEBUG | Detailed information during development and debugging, not output by default in production | | INFO | General runtime information, such as request records, service startup | | WARNING | Warning information, potential issues but doesn't affect current operation | | ERROR | Error information, some functionality failed but service is still running | | CRITICAL | Critical error, may cause service to stop | > In Debug mode, Flask automatically sets the log level to DEBUG. In production, it should be set to INFO or WARNING as needed to avoid outputting too much useless information. * * * ## Configure Log Output Write logs to files for later analysis and troubleshooting: ## Example import logging from logging.handlers import RotatingFileHandler # Configure file log handler - log file automatically rotates after reaching 10MB handler = RotatingFileHandler( "tutorial_app.log",# Log file path maxBytes=10 * 1024 * 1024,# Maximum 10MB per file backupCount=5# Keep the last 5 backup files ) # Set log format handler.setFormatter(logging.Formatter( "[%(asctime)s] %(levelname)s in %(module)s: %(message)s" )) # Add handler to Flask's logger app.logger.addHandler(handler) app.logger.setLevel(logging.INFO) * * * ## Catch Unhandled Exceptions Using app.errorhandler(500) can catch unhandled exceptions and log them: ## Example import traceback @app.errorhandler(500) def internal_error(error): # Log the full exception stack app.logger.error("Internal server error:n%s",traceback.format_exc()) # Show a friendly error page to the user return"""

500 - Internal Server Error

Sorry, the server encountered an unexpected error. We have recorded the issue, please try

← Flask DeploymentFlask Orm β†’