11import secrets
22import os
33import asyncio
4- from .routing import Router
4+ from .routing import Router , NotFound , MethodNotAllowed
55from .request import Request
66from .response import Response , HTMLResponse , configure_template_env
77from .auth import init_auth , get_current_user
@@ -79,9 +79,9 @@ def decorator(func):
7979
8080 async def _asgi_app_handler (self , scope , receive , send ):
8181 req = scope ['jsweb.request' ]
82-
83- handler , params = self .router .resolve (req .path , req .method )
84- if handler :
82+ try :
83+ handler , params = self .router .resolve (req .path , req .method )
84+
8585 # Support both sync and async handlers
8686 if asyncio .iscoroutinefunction (handler ):
8787 response = await handler (req , ** params )
@@ -94,14 +94,16 @@ async def _asgi_app_handler(self, scope, receive, send):
9494 if not isinstance (response , Response ):
9595 raise TypeError (f"View function did not return a Response object (got { type (response ).__name__ } )" )
9696
97- if hasattr (req , 'new_csrf_token_generated' ) and req .new_csrf_token_generated :
98- response .set_cookie ("csrf_token" , req .csrf_token , httponly = False , samesite = 'Lax' )
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 )
99103
100- await response ( scope , receive , send )
101- return
104+ if hasattr ( req , 'new_csrf_token_generated' ) and req . new_csrf_token_generated :
105+ response . set_cookie ( "csrf_token" , req . csrf_token , httponly = False , samesite = 'Lax' )
102106
103- # 404 Not Found
104- response = HTMLResponse ("<h1>404 Not Found</h1>" , status_code = 404 )
105107 await response (scope , receive , send )
106108
107109
0 commit comments