Consider a Django middleware that catches exceptions during request processing. What is the typical behavior when an exception is raised inside the __call__ method of middleware?
class ExceptionMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: response = self.get_response(request) except Exception as e: return self.handle_exception(request, e) return response def handle_exception(self, request, exception): return HttpResponse('Error handled', status=500)
Think about how exception handling works in Python and how middleware can intercept errors.
When an exception is raised inside the __call__ method, the middleware can catch it and return a custom response, preventing the server from crashing.
Which option contains a syntax error that will prevent this middleware from running?
class ExceptionMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try response = self.get_response(request) except Exception as e: return self.handle_exception(request, e) return response def handle_exception(self, request, exception): return HttpResponse('Error', status=500)
Check the syntax of the try-except block carefully.
The try statement must end with a colon. Missing it causes a SyntaxError.
Given the following middleware, why does it fail to catch exceptions raised in views?
class ExceptionMiddleware: def __init__(self, get_response): self.get_response = get_response def process_exception(self, request, exception): return HttpResponse('Exception caught', status=500) def __call__(self, request): response = self.get_response(request) return response
Think about how Django calls process_exception and middleware styles.
In new-style middleware, process_exception is not called automatically. Exceptions must be caught in __call__.
What status code will the client receive when an exception is raised in the view and handled by this middleware?
class ExceptionMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: response = self.get_response(request) except Exception: return HttpResponse('Handled error', status=418) return response
Look at the status code set in the HttpResponse returned on exception.
The middleware returns a response with status 418 when an exception occurs.
In Django, middleware order matters. Where should exception middleware be placed in the MIDDLEWARE list to catch exceptions from all views and other middleware?
Think about how Django processes middleware in order and how exceptions propagate.
Django processes middleware top-down on request (first to last) and bottom-up on response (last to first). Placing exception middleware first ensures it wraps all others and can catch exceptions from them.