Bird
Raised Fist0
Djangoframework~20 mins

Exception middleware in Django - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Exception Middleware Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when an exception is raised in Django middleware?

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?

Django
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)
AThe middleware ignores the exception and lets it propagate to the next middleware or view.
BThe middleware catches the exception and returns a custom error response without crashing the server.
CThe middleware logs the exception but still returns the original response from the view.
DThe middleware crashes the server immediately without returning any response.
Attempts:
2 left
💡 Hint

Think about how exception handling works in Python and how middleware can intercept errors.

📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this Django exception middleware snippet

Which option contains a syntax error that will prevent this middleware from running?

Django
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)
AMissing parentheses in HttpResponse call.
BIncorrect indentation of the except block.
CMissing self parameter in handle_exception method.
DMissing colon after try statement.
Attempts:
2 left
💡 Hint

Check the syntax of the try-except block carefully.

🔧 Debug
advanced
2:00remaining
Why does this exception middleware fail to catch exceptions?

Given the following middleware, why does it fail to catch exceptions raised in views?

Django
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
ABecause <code>process_exception</code> is never called unless middleware is old-style and registered properly.
BBecause <code>__call__</code> method does not have a try-except block to catch exceptions.
CBecause the middleware does not import HttpResponse.
DBecause the middleware returns the response before calling <code>process_exception</code>.
Attempts:
2 left
💡 Hint

Think about how Django calls process_exception and middleware styles.

state_output
advanced
2:00remaining
What is the response status code after exception handling in this middleware?

What status code will the client receive when an exception is raised in the view and handled by this middleware?

Django
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
A200
B500
C418
D404
Attempts:
2 left
💡 Hint

Look at the status code set in the HttpResponse returned on exception.

🧠 Conceptual
expert
2:00remaining
Which middleware order ensures exception middleware catches errors from all views and other middleware?

In Django, middleware order matters. Where should exception middleware be placed in the MIDDLEWARE list to catch exceptions from all views and other middleware?

AAt the very beginning (first in the list).
BAt the very end (last in the list).
CIn the middle, after authentication middleware.
DAnywhere, order does not affect exception catching.
Attempts:
2 left
💡 Hint

Think about how Django processes middleware in order and how exceptions propagate.

Practice

(1/5)
1. What is the main purpose of exception middleware in Django?
easy
A. To catch errors during request processing and handle them gracefully
B. To speed up database queries
C. To serve static files like images and CSS
D. To manage user authentication sessions

Solution

  1. Step 1: Understand middleware role

    Middleware processes requests and responses in Django, and exception middleware specifically handles errors.
  2. Step 2: Identify exception middleware purpose

    Its job is to catch exceptions during request handling and provide friendly error messages or logging.
  3. Final Answer:

    To catch errors during request processing and handle them gracefully -> Option A
  4. Quick Check:

    Exception middleware = catch errors [OK]
Hint: Exception middleware catches errors in requests [OK]
Common Mistakes:
  • Confusing middleware with static file serving
  • Thinking it manages database queries
  • Assuming it handles user sessions
2. Which method must be implemented in a Django exception middleware class to process requests?
easy
A. __init__
B. __call__
C. process_exception
D. handle_request

Solution

  1. Step 1: Recall middleware structure

    Django middleware classes require an __init__ and a __call__ method to be callable.
  2. Step 2: Identify request processing method

    The __call__ method is called for each request and is where exception handling happens.
  3. Final Answer:

    __call__ -> Option B
  4. Quick Check:

    Request processing method = __call__ [OK]
Hint: Middleware uses __call__ to handle requests [OK]
Common Mistakes:
  • Choosing process_exception which is for old-style middleware
  • Confusing __init__ as request handler
  • Inventing non-existent handle_request method
3. Given this middleware snippet, what will be the output if a ZeroDivisionError occurs during request processing?
class ExceptionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        try:
            response = self.get_response(request)
        except ZeroDivisionError:
            return HttpResponse('Division error caught')
        return response
medium
A. The original response from get_response
B. A server error 500 page
C. No response, request hangs
D. HttpResponse with text 'Division error caught'

Solution

  1. Step 1: Analyze try-except block

    The middleware calls get_response inside try; if ZeroDivisionError occurs, it returns a custom HttpResponse.
  2. Step 2: Determine output on error

    When ZeroDivisionError happens, the except block returns HttpResponse('Division error caught').
  3. Final Answer:

    HttpResponse with text 'Division error caught' -> Option D
  4. Quick Check:

    Error caught returns custom response [OK]
Hint: Exception triggers except block response [OK]
Common Mistakes:
  • Assuming original response is returned despite error
  • Expecting default 500 error page
  • Thinking request will hang without response
4. Identify the error in this exception middleware code:
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:
            print('Error:', e)
        return response
medium
A. No __init__ method defined
B. Incorrect method name __call__
C. Missing return statement inside except block
D. Using print instead of logging

Solution

  1. Step 1: Check exception handling flow

    If an exception occurs, except block prints error but does not return a response.
  2. Step 2: Understand middleware response requirement

    Middleware must always return a response; missing return in except causes NameError or no response.
  3. Final Answer:

    Missing return statement inside except block -> Option C
  4. Quick Check:

    Exception block must return response [OK]
Hint: Always return response in except block [OK]
Common Mistakes:
  • Ignoring missing return causes runtime error
  • Thinking print is enough for error handling
  • Confusing method names or missing __init__
5. You want to create exception middleware that logs errors and returns a JSON error response with status 500. Which code snippet correctly implements this behavior?
import json
from django.http import HttpResponse

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:
            # Log the error
            print(f'Error: {e}')
            # Return JSON error response
            error_content = json.dumps({'error': 'Server error'})
            return HttpResponse(error_content, content_type='application/json', status=500)
        return response
hard
A. Correctly logs error and returns JSON response with status 500
B. Does not log error, only returns JSON response
C. Returns HTML response instead of JSON
D. Raises exception instead of handling it

Solution

  1. Step 1: Check error logging

    The except block prints the error, which acts as logging here.
  2. Step 2: Verify JSON response and status

    It returns HttpResponse with JSON content, correct content_type, and status 500.
  3. Final Answer:

    Correctly logs error and returns JSON response with status 500 -> Option A
  4. Quick Check:

    Logs error + JSON 500 response [OK]
Hint: Print error then return JSON with status 500 [OK]
Common Mistakes:
  • Forgetting to set content_type to application/json
  • Not returning response in except block
  • Raising exception instead of handling