-
Notifications
You must be signed in to change notification settings - Fork 1
Exception mapper
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:
-
Purpose: Catch all exceptions from the resource layer and inform the user appropriately.
-
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.
-
Solution: Use the
exception_mapperto register specific messages for exceptions, freeing your cog's methods fromtry...exceptblocks.
-
Locate
__register_exceptionsMethod: Inconfig/environment/context/application_context.py, find the__register_exceptionsmethod. -
Register Exceptions: Pass a list of tuples to the
__register_exceptionsmethod. 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.
- You can register a base exception. The base will only be checked if a more specific child exception does not exist.
⚠️ Do not registerExceptionorBaseException. 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.