frontend error management enhancement
This commit is contained in:
@@ -7,6 +7,7 @@ This module provides classes and functions for:
|
||||
- Unified exception handling for all application exceptions
|
||||
- Consistent error response formatting
|
||||
- Comprehensive logging with structured data
|
||||
- Context-aware HTML error pages
|
||||
"""
|
||||
|
||||
import logging
|
||||
@@ -17,6 +18,8 @@ from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, RedirectResponse
|
||||
|
||||
from .base import WizamartException
|
||||
from .error_renderer import ErrorPageRenderer
|
||||
from middleware.context_middleware import RequestContext, get_request_context
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -26,7 +29,7 @@ def setup_exception_handlers(app):
|
||||
|
||||
@app.exception_handler(WizamartException)
|
||||
async def custom_exception_handler(request: Request, exc: WizamartException):
|
||||
"""Handle custom exceptions."""
|
||||
"""Handle custom exceptions with context-aware rendering."""
|
||||
|
||||
# Special handling for 401 on HTML page requests (redirect to login)
|
||||
if exc.status_code == 401 and _is_html_page_request(request):
|
||||
@@ -39,16 +42,10 @@ def setup_exception_handlers(app):
|
||||
}
|
||||
)
|
||||
|
||||
# Redirect to appropriate login page
|
||||
if request.url.path.startswith("/admin"):
|
||||
logger.debug("Redirecting to /admin/login")
|
||||
return RedirectResponse(url="/admin/login", status_code=302)
|
||||
elif "/vendor/" in request.url.path:
|
||||
logger.debug("Redirecting to /vendor/login")
|
||||
return RedirectResponse(url="/vendor/login", status_code=302)
|
||||
# If neither, fall through to JSON response
|
||||
logger.debug("No specific redirect path matched, returning JSON")
|
||||
# Redirect to appropriate login page based on context
|
||||
return _redirect_to_login(request)
|
||||
|
||||
# Log the exception
|
||||
logger.error(
|
||||
f"Custom exception in {request.method} {request.url}: "
|
||||
f"{exc.error_code} - {exc.message}",
|
||||
@@ -62,6 +59,25 @@ def setup_exception_handlers(app):
|
||||
}
|
||||
)
|
||||
|
||||
# Check if this is an API request
|
||||
if _is_api_request(request):
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content=exc.to_dict()
|
||||
)
|
||||
|
||||
# Check if this is an HTML page request
|
||||
if _is_html_page_request(request):
|
||||
return ErrorPageRenderer.render_error_page(
|
||||
request=request,
|
||||
status_code=exc.status_code,
|
||||
error_code=exc.error_code,
|
||||
message=exc.message,
|
||||
details=exc.details,
|
||||
show_debug=True, # Will be filtered by ErrorPageRenderer based on user role
|
||||
)
|
||||
|
||||
# Default to JSON for unknown request types
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content=exc.to_dict()
|
||||
@@ -83,6 +99,29 @@ def setup_exception_handlers(app):
|
||||
}
|
||||
)
|
||||
|
||||
# Check if this is an API request
|
||||
if _is_api_request(request):
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={
|
||||
"error_code": f"HTTP_{exc.status_code}",
|
||||
"message": exc.detail,
|
||||
"status_code": exc.status_code,
|
||||
}
|
||||
)
|
||||
|
||||
# Check if this is an HTML page request
|
||||
if _is_html_page_request(request):
|
||||
return ErrorPageRenderer.render_error_page(
|
||||
request=request,
|
||||
status_code=exc.status_code,
|
||||
error_code=f"HTTP_{exc.status_code}",
|
||||
message=exc.detail,
|
||||
details={},
|
||||
show_debug=True,
|
||||
)
|
||||
|
||||
# Default to JSON
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={
|
||||
@@ -130,6 +169,32 @@ def setup_exception_handlers(app):
|
||||
clean_error[key] = value
|
||||
clean_errors.append(clean_error)
|
||||
|
||||
# Check if this is an API request
|
||||
if _is_api_request(request):
|
||||
return JSONResponse(
|
||||
status_code=422,
|
||||
content={
|
||||
"error_code": "VALIDATION_ERROR",
|
||||
"message": "Request validation failed",
|
||||
"status_code": 422,
|
||||
"details": {
|
||||
"validation_errors": clean_errors
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
# Check if this is an HTML page request
|
||||
if _is_html_page_request(request):
|
||||
return ErrorPageRenderer.render_error_page(
|
||||
request=request,
|
||||
status_code=422,
|
||||
error_code="VALIDATION_ERROR",
|
||||
message="Request validation failed",
|
||||
details={"validation_errors": clean_errors},
|
||||
show_debug=True,
|
||||
)
|
||||
|
||||
# Default to JSON
|
||||
return JSONResponse(
|
||||
status_code=422,
|
||||
content={
|
||||
@@ -137,7 +202,7 @@ def setup_exception_handlers(app):
|
||||
"message": "Request validation failed",
|
||||
"status_code": 422,
|
||||
"details": {
|
||||
"validation_errors": clean_errors # Use cleaned errors
|
||||
"validation_errors": clean_errors
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -156,6 +221,29 @@ def setup_exception_handlers(app):
|
||||
}
|
||||
)
|
||||
|
||||
# Check if this is an API request
|
||||
if _is_api_request(request):
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={
|
||||
"error_code": "INTERNAL_SERVER_ERROR",
|
||||
"message": "Internal server error",
|
||||
"status_code": 500,
|
||||
}
|
||||
)
|
||||
|
||||
# Check if this is an HTML page request
|
||||
if _is_html_page_request(request):
|
||||
return ErrorPageRenderer.render_error_page(
|
||||
request=request,
|
||||
status_code=500,
|
||||
error_code="INTERNAL_SERVER_ERROR",
|
||||
message="Internal server error",
|
||||
details={},
|
||||
show_debug=True,
|
||||
)
|
||||
|
||||
# Default to JSON
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={
|
||||
@@ -170,97 +258,33 @@ def setup_exception_handlers(app):
|
||||
"""Handle all 404 errors with consistent format."""
|
||||
logger.warning(f"404 Not Found: {request.method} {request.url}")
|
||||
|
||||
# Check if this is a browser request (wants HTML)
|
||||
accept_header = request.headers.get("accept", "")
|
||||
# Check if this is an API request
|
||||
if _is_api_request(request):
|
||||
return JSONResponse(
|
||||
status_code=404,
|
||||
content={
|
||||
"error_code": "ENDPOINT_NOT_FOUND",
|
||||
"message": f"Endpoint not found: {request.url.path}",
|
||||
"status_code": 404,
|
||||
"details": {
|
||||
"path": request.url.path,
|
||||
"method": request.method
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
# Browser requests typically have "text/html" in accept header
|
||||
# API requests typically have "application/json"
|
||||
if "text/html" in accept_header:
|
||||
# Return simple HTML 404 page for browser
|
||||
from fastapi.responses import HTMLResponse
|
||||
# Check if this is an HTML page request
|
||||
if _is_html_page_request(request):
|
||||
return ErrorPageRenderer.render_error_page(
|
||||
request=request,
|
||||
status_code=404,
|
||||
error_code="ENDPOINT_NOT_FOUND",
|
||||
message=f"The page you're looking for doesn't exist or has been moved.",
|
||||
details={"path": request.url.path},
|
||||
show_debug=True,
|
||||
)
|
||||
|
||||
html_content = f"""
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>404 - Page Not Found</title>
|
||||
<style>
|
||||
* {{
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}}
|
||||
body {{
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: white;
|
||||
}}
|
||||
.container {{
|
||||
text-align: center;
|
||||
padding: 2rem;
|
||||
max-width: 600px;
|
||||
}}
|
||||
h1 {{
|
||||
font-size: 8rem;
|
||||
font-weight: 700;
|
||||
margin-bottom: 1rem;
|
||||
text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
|
||||
}}
|
||||
h2 {{
|
||||
font-size: 2rem;
|
||||
font-weight: 400;
|
||||
margin-bottom: 1rem;
|
||||
}}
|
||||
p {{
|
||||
font-size: 1.2rem;
|
||||
margin-bottom: 2rem;
|
||||
opacity: 0.9;
|
||||
}}
|
||||
.btn {{
|
||||
display: inline-block;
|
||||
padding: 1rem 2.5rem;
|
||||
background: white;
|
||||
color: #667eea;
|
||||
text-decoration: none;
|
||||
border-radius: 50px;
|
||||
font-weight: 600;
|
||||
transition: all 0.3s ease;
|
||||
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
|
||||
}}
|
||||
.btn:hover {{
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 20px rgba(0,0,0,0.3);
|
||||
}}
|
||||
.path {{
|
||||
margin-top: 2rem;
|
||||
font-size: 0.9rem;
|
||||
opacity: 0.7;
|
||||
font-family: 'Courier New', monospace;
|
||||
word-break: break-all;
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1>404</h1>
|
||||
<h2>Page Not Found</h2>
|
||||
<p>Sorry, the page you're looking for doesn't exist or has been moved.</p>
|
||||
<a href="/" class="btn">Go Home</a>
|
||||
<div class="path">Path: {request.url.path}</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
return HTMLResponse(content=html_content, status_code=404)
|
||||
|
||||
# Return JSON for API requests
|
||||
# Default to JSON
|
||||
return JSONResponse(
|
||||
status_code=404,
|
||||
content={
|
||||
@@ -275,6 +299,15 @@ def setup_exception_handlers(app):
|
||||
)
|
||||
|
||||
|
||||
def _is_api_request(request: Request) -> bool:
|
||||
"""
|
||||
Check if the request is for an API endpoint.
|
||||
|
||||
API requests ALWAYS return JSON.
|
||||
"""
|
||||
return request.url.path.startswith("/api/")
|
||||
|
||||
|
||||
def _is_html_page_request(request: Request) -> bool:
|
||||
"""
|
||||
Check if the request is for an HTML page (not an API endpoint).
|
||||
@@ -295,7 +328,7 @@ def _is_html_page_request(request: Request) -> bool:
|
||||
)
|
||||
|
||||
# Don't redirect API calls
|
||||
if "/api/" in request.url.path:
|
||||
if _is_api_request(request):
|
||||
logger.debug("Not HTML page: API endpoint")
|
||||
return False
|
||||
|
||||
@@ -315,10 +348,34 @@ def _is_html_page_request(request: Request) -> bool:
|
||||
logger.debug(f"Not HTML page: Accept header doesn't include text/html: {accept_header}")
|
||||
return False
|
||||
|
||||
logger.debug("IS HTML page request - will redirect on 401")
|
||||
logger.debug("IS HTML page request")
|
||||
return True
|
||||
|
||||
|
||||
def _redirect_to_login(request: Request) -> RedirectResponse:
|
||||
"""
|
||||
Redirect to appropriate login page based on request context.
|
||||
|
||||
Uses context detection to determine admin vs vendor vs shop login.
|
||||
"""
|
||||
context_type = get_request_context(request)
|
||||
|
||||
if context_type == RequestContext.ADMIN:
|
||||
logger.debug("Redirecting to /admin/login")
|
||||
return RedirectResponse(url="/admin/login", status_code=302)
|
||||
elif context_type == RequestContext.VENDOR_DASHBOARD:
|
||||
logger.debug("Redirecting to /vendor/login")
|
||||
return RedirectResponse(url="/vendor/login", status_code=302)
|
||||
elif context_type == RequestContext.SHOP:
|
||||
# For shop context, redirect to shop login (customer login)
|
||||
logger.debug("Redirecting to /shop/login")
|
||||
return RedirectResponse(url="/shop/login", status_code=302)
|
||||
else:
|
||||
# Fallback to root for unknown contexts
|
||||
logger.debug("Unknown context, redirecting to /")
|
||||
return RedirectResponse(url="/", status_code=302)
|
||||
|
||||
|
||||
# Utility functions for common exception scenarios
|
||||
def raise_not_found(resource_type: str, identifier: str) -> None:
|
||||
"""Convenience function to raise ResourceNotFoundException."""
|
||||
|
||||
Reference in New Issue
Block a user