Project 6 · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does this print?
class AppError(Exception):
    def __init__(self, *args):
        super().__init__(args)

e = AppError('message', 10)
print(e.args)
2. What does this print?
class WidgetError(Exception):
    message = 'generic'
    def __init__(self, *args):
        if args:
            self.message = args[0]
        super().__init__(*args)

class StockError(WidgetError):
    message = 'out of stock'

a = StockError()
b = StockError('only 2 left')
print(a.message, '|', b.message, '|', StockError.message)
3. What does this print?
from http import HTTPStatus
s = HTTPStatus.BAD_REQUEST
print(s.value, s.phrase)
4. What does this print?
import json
from http import HTTPStatus
print(json.dumps({'code': HTTPStatus.NOT_FOUND}))
5. Which handler runs?
class WidgetException(Exception): pass
class CheckoutException(WidgetException): pass
class PricingException(CheckoutException): pass
class InvalidCouponCodeException(PricingException): pass

try:
    raise InvalidCouponCodeException('expired')
except CheckoutException:
    print('checkout handler')
except PricingException:
    print('pricing handler')
except WidgetException:
    print('widget handler')
6. What does this print?
class WidgetException(Exception):
    message = 'Generic.'
    def __init__(self, *args, customer_message=None):
        if args:
            self.message = args[0]
        super().__init__(*args)
        self.customer_message = customer_message or self.message

e = WidgetException('internal detail', 'for the customer')
print(e.customer_message)
7. What does this print?
import traceback
e = ValueError('never raised')
print(traceback.format_exception(e))

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: The exception hierarchy

Write the exception classes for the widget shop. Every class must derive from the class shown above it in this tree (a class's only base is its parent):

text WidgetException (derives from Exception) ├── SupplierException │ ├── NotManufacturedException │ ├── ProductionDelayedException │ └── ShippingDelayedException └── CheckoutException ├── InventoryException │ └── OutOfStockException └── PricingException ├── InvalidCouponCodeException └── CannotStackCouponException

Every class must define its own class attribute message: a non-empty string describing that exception, different for every class (e.g. 'Inventory out of stock.').

Hints (2)
  1. Each category (SupplierException, CheckoutException, InventoryException, PricingException) is a class too, with the leaves deriving from it.
  2. A class body consisting of just message = '...' is enough.
Show a solution
class WidgetException(Exception):
    """Base exception for the Widget application."""
    message = 'Generic Widget exception.'

class SupplierException(WidgetException):
    message = 'Supplier exception.'

class NotManufacturedException(SupplierException):
    message = 'Widget is no longer manufactured by supplier.'

class ProductionDelayedException(SupplierException):
    message = 'Widget production has been delayed by supplier.'

class ShippingDelayedException(SupplierException):
    message = 'Widget shipping has been delayed by supplier.'

class CheckoutException(WidgetException):
    message = 'Checkout exception.'

class InventoryException(CheckoutException):
    message = 'Checkout inventory exception.'

class OutOfStockException(InventoryException):
    message = 'Inventory out of stock.'

class PricingException(CheckoutException):
    message = 'Checkout pricing exception.'

class InvalidCouponCodeException(PricingException):
    message = 'Invalid checkout coupon code.'

class CannotStackCouponException(PricingException):
    message = 'Cannot stack checkout coupon codes.'

Exercise 2: Internal and customer messages

Give WidgetException an __init__(self, *args, customer_message=None) so that:

- with positional arguments, the first one becomes the instance's message, and all of them are kept in args; - with no arguments, message stays the class default, and args is (message,) so str(ex) is the default message; - customer_message (keyword-only) is stored on the instance, and defaults to message when not given.

This must also work for subclasses that only override the class attribute message.

Hints (2)
  1. self.message = args[0] creates an instance attribute; reading self.message without assigning it finds the class attribute.
  2. Unpack when calling the parent: super().__init__(*args). If args is empty, use (self.message,) instead.
Show a solution
class WidgetException(Exception):
    """Base exception for the Widget application."""
    message = 'Generic Widget exception.'

    def __init__(self, *args, customer_message=None):
        if args:
            self.message = args[0]
        else:
            args = (self.message,)
        super().__init__(*args)
        self.customer_message = (customer_message if customer_message is not None
                                 else self.message)

class OutOfStockException(WidgetException):
    message = 'Inventory out of stock.'

Exercise 3: HTTP status and JSON response

The hierarchy and __init__ are given. Add:

- an http_status class attribute: HTTPStatus.INTERNAL_SERVER_ERROR on WidgetException (inherited by everything), overridden with HTTPStatus.BAD_REQUEST on InvalidCouponCodeException and CannotStackCouponException; - a method to_json() on WidgetException that returns a JSON string of an object with the keys: - code: the status number, e.g. 400; - message: the status phrase, a colon and the customer message, e.g. "Bad Request: Sorry, this coupon has expired."; - category: the exception's class name; - time_utc: the current time as an ISO 8601 string with the UTC offset (use datetime.now(timezone.utc).isoformat()).

Hints (3)
  1. Only three classes need an http_status line; the rest inherit the base class's value.
  2. HTTPStatus members have .value (e.g. 400) and .phrase (e.g. 'Bad Request').
  3. Build a dict and return json.dumps(the_dict).
Show a solution
import json
from datetime import datetime, timezone
from http import HTTPStatus

class WidgetException(Exception):
    """Base exception for the Widget application."""
    message = 'Generic Widget exception.'
    http_status = HTTPStatus.INTERNAL_SERVER_ERROR

    def __init__(self, *args, customer_message=None):
        if args:
            self.message = args[0]
        else:
            args = (self.message,)
        super().__init__(*args)
        self.customer_message = (customer_message if customer_message is not None
                                 else self.message)

    def to_json(self):
        response = {
            'code': self.http_status.value,
            'message': f'{self.http_status.phrase}: {self.customer_message}',
            'category': type(self).__name__,
            'time_utc': datetime.now(timezone.utc).isoformat(),
        }
        return json.dumps(response)

class SupplierException(WidgetException):
    message = 'Supplier exception.'

class NotManufacturedException(SupplierException):
    message = 'Widget is no longer manufactured by supplier.'

class ProductionDelayedException(SupplierException):
    message = 'Widget production has been delayed by supplier.'

class ShippingDelayedException(SupplierException):
    message = 'Widget shipping has been delayed by supplier.'

class CheckoutException(WidgetException):
    message = 'Checkout exception.'

class InventoryException(CheckoutException):
    message = 'Checkout inventory exception.'

class OutOfStockException(InventoryException):
    message = 'Inventory out of stock.'

class PricingException(CheckoutException):
    message = 'Checkout pricing exception.'

class InvalidCouponCodeException(PricingException):
    message = 'Invalid checkout coupon code.'
    http_status = HTTPStatus.BAD_REQUEST

class CannotStackCouponException(PricingException):
    message = 'Cannot stack checkout coupon codes.'
    http_status = HTTPStatus.BAD_REQUEST

Exercise 4: Logging with the traceback

Add two members to WidgetException:

- a property traceback_lines returning the formatted traceback of the exception as a list of strings (exactly what traceback.format_exception(self) gives); - a method log_exception() that builds a dict with the keys type (class name), http_status (the number, e.g. 500), message, args (the positional arguments after the message), time_utc (a UTC ISO timestamp string) and traceback (the traceback_lines list), prints one line starting with EXCEPTION that contains the type and message, and returns the dict.

Hints (3)
  1. Inside a method, the exception is self, so traceback.format_exception(self) formats it (Python 3.10+).
  2. self.args[1:] gives the positional arguments after the message.
  3. Decorate traceback_lines with @property, and remember to return the record from log_exception.
Show a solution
import json
import traceback
from datetime import datetime, timezone
from http import HTTPStatus

class WidgetException(Exception):
    """Base exception for the Widget application."""
    message = 'Generic Widget exception.'
    http_status = HTTPStatus.INTERNAL_SERVER_ERROR

    def __init__(self, *args, customer_message=None):
        if args:
            self.message = args[0]
        else:
            args = (self.message,)
        super().__init__(*args)
        self.customer_message = (customer_message if customer_message is not None
                                 else self.message)

    @property
    def traceback_lines(self):
        return traceback.format_exception(self)

    def log_exception(self):
        record = {
            'type': type(self).__name__,
            'http_status': self.http_status.value,
            'message': self.message,
            'args': self.args[1:],
            'time_utc': datetime.now(timezone.utc).isoformat(),
            'traceback': self.traceback_lines,
        }
        print(f"EXCEPTION {record['time_utc']}: {record['type']}: {record['message']}")
        return record

class InvalidCouponCodeException(WidgetException):
    message = 'Invalid checkout coupon code.'
    http_status = HTTPStatus.BAD_REQUEST