Skip to content

Exception mapper

Babouche edited this page Jul 30, 2024 · 1 revision

To handle exceptions in your resource layer and notify the user accordingly, you can implement an exception_mapper to map specific exceptions to user-friendly messages. This allows you to avoid repetitive try...except blocks in your cogs and centralize exception handling. Here’s how to set it up:

Step-by-Step Guide

  1. Purpose: Catch all exceptions from the resource layer and inform the user appropriately.

  2. Problem:

    • When a user tries to join a game that is full, you raise an exception.
    • To notify the user, you could catch the exception in the cog and return a message.
    • However, if there are multiple error messages and games, adding catches for each becomes cumbersome.
  3. Solution: Use the exception_mapper to register specific messages for exceptions, freeing your cog's methods from try...except blocks.

How to Register an Exception

  1. Locate __register_exceptions Method: In config/environment/context/application_context.py, find the __register_exceptions method.

  2. Register Exceptions: Pass a list of tuples to the __register_exceptions method. Each tuple contains:

    • The exception to catch.
    • The reply message associated with the exception.

    Example:

    self.__register_exceptions(
        [
            (InvalidFormatException, ReplyMessage.INVALID_FORMAT),
            (MissingArgumentsException, ReplyMessage.MISSING_ARGUMENTS_IN_COMMAND),
        ]
    )
    • The first element of the tuple is the exception you want to catch.
    • The second element is the reply message associated with the exception.

✏️ Notes:

  • You can register a base exception. The base will only be checked if a more specific child exception does not exist.
  • ⚠️ Do not register Exception or BaseException. If an unregistered exception occurs, the cog will handle it and log the missing error.

By using this approach, you ensure that your code remains clean and maintainable, with centralized exception handling that provides consistent user feedback.

Clone this wiki locally