0
0
Djangoframework~10 mins

Exception middleware in Django - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a middleware class that catches exceptions.

Django
class ExceptionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        try:
            response = self.get_response(request)
        except [1] as e:
            response = self.handle_exception(e)
        return response

    def handle_exception(self, exception):
        # Handle exception here
        pass
Drag options to blanks, or click blank then click option'
AError
Brequest
Cresponse
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Error' which is not a base exception class in Python.
Catching 'request' or 'response' which are not exception types.
2fill in blank
medium

Complete the code to import the middleware in Django settings.

Django
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'myapp.middleware.[1]',
    'django.middleware.common.CommonMiddleware',
]
Drag options to blanks, or click blank then click option'
ASecurityMiddleware
BExceptionMiddleware
CCommonMiddleware
DSessionMiddleware
Attempts:
3 left
💡 Hint
Common Mistakes
Using built-in middleware names instead of the custom one.
Misspelling the middleware class name.
3fill in blank
hard

Fix the error in the middleware method to correctly return an HTTP response on exception.

Django
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:
            response = [1]('An error occurred', status=500)
        return response
Drag options to blanks, or click blank then click option'
AHttpResponse
BHttpRequest
CHttp404
DHttpError
Attempts:
3 left
💡 Hint
Common Mistakes
Using HttpRequest which is for requests, not responses.
Using Http404 which raises an exception, not returns a response.
4fill in blank
hard

Fill both blanks to log the exception message and return a simple error response.

Django
import logging
from django.http import HttpResponse

logger = logging.getLogger(__name__)

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:
            logger.[1](str(e))
            response = HttpResponse('Error occurred', status=[2])
        return response
Drag options to blanks, or click blank then click option'
Aerror
Bwarning
C404
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Using logger.warning which is less severe than error.
Returning status 404 which means not found, not server error.
5fill in blank
hard

Fill all three blanks to create a middleware that logs exceptions, returns JSON error response, and sets content type.

Django
import logging
import json
from django.http import HttpResponse

logger = logging.getLogger(__name__)

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:
            logger.[1](str(e))
            error_content = json.dumps({'error': 'Server error'})
            response = HttpResponse(error_content, status=[2])
            response['Content-Type'] = [3]
        return response
Drag options to blanks, or click blank then click option'
Aerror
B500
C'application/json'
Dwarning
Attempts:
3 left
💡 Hint
Common Mistakes
Using logger.warning instead of error.
Setting wrong content type like 'text/html'.
Using status 404 instead of 500.