Skip to content

Commit 2c93ec2

Browse files
committed
Dev : Error handle updates
1 parent c488a13 commit 2c93ec2

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

jsweb/app.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import asyncio
44
from .routing import Router, NotFound, MethodNotAllowed
55
from .request import Request
6-
from .response import Response, HTMLResponse, configure_template_env
6+
from .response import Response, HTMLResponse, configure_template_env, JSONResponse
77
from .auth import init_auth, get_current_user
88
from .middleware import StaticFilesMiddleware, DBSessionMiddleware, CSRFMiddleware
99
from .blueprints import Blueprint
@@ -81,7 +81,20 @@ async def _asgi_app_handler(self, scope, receive, send):
8181
req = scope['jsweb.request']
8282
try:
8383
handler, params = self.router.resolve(req.path, req.method)
84-
84+
except NotFound as e:
85+
response = JSONResponse({"error": str(e)}, status_code=404)
86+
await response(scope,receive, send)
87+
return
88+
except MethodNotAllowed as e:
89+
response = JSONResponse({"error": str(e)}, status_code=405)
90+
await response(scope, receive, send)
91+
return
92+
except Exception:
93+
response = JSONResponse({"error": "Internal Server Error"}, status_code=500)
94+
await response(scope, receive, send)
95+
return
96+
97+
if handler:
8598
# Support both sync and async handlers
8699
if asyncio.iscoroutinefunction(handler):
87100
response = await handler(req, **params)
@@ -94,12 +107,7 @@ async def _asgi_app_handler(self, scope, receive, send):
94107
if not isinstance(response, Response):
95108
raise TypeError(f"View function did not return a Response object (got {type(response).__name__})")
96109

97-
except NotFound:
98-
response = HTMLResponse("<h1>404 Not Found</h1>", status_code=404)
99-
except MethodNotAllowed:
100-
response = HTMLResponse("<h1>405 Method Not Allowed</h1>", status_code=405)
101-
except Exception as e:
102-
response = HTMLResponse(f"<h1>500 Internal Server Error</h1><p>{e}</p>", status_code=500)
110+
103111

104112
if hasattr(req, 'new_csrf_token_generated') and req.new_csrf_token_generated:
105113
response.set_cookie("csrf_token", req.csrf_token, httponly=False, samesite='Lax')

0 commit comments

Comments
 (0)