BOB Docs
APIFeatures

Exception Registry

API Exceptions Handling

We have created a simple exception handler that processes raised exceptions. This handler checks whether the exception is an instance of ApiException. If it is, the handler automatically creates a response based on the exception details.

This approach centralizes exception handling, allowing you to decide what message your user sees directly in the code while keeping a single place for managing exceptions.

Example

@api.exception_handler(Exception)
def api_exception_handler(request, exc):
    """
    Handles exceptions raised in API requests.
 
    - If the exception is an instance of `ApiException`, it sends a response with a
      user-friendly error message and a specific HTTP status code.
    - For other exceptions, it logs the exception details for debugging and
      provides a generic error response.
 
    :param request: The incoming request object.
    :param exc: The raised exception.
    :return: A JSON response containing the error message and status code.
    """
    if isinstance(exc, ApiException):
        return api.create_response(
            request,
            {"message": exc.api_client_message},
            status=exc.status_code,
        )
    else:
        logger.exception(exc)
        return api.create_response(
            request,
            {"message": "An unexpected error occurred. Please try again later."},
            status=500,
        )

This required creating the ApiException class, which allows us to define custom exception types along with HTTP messages and status codes.

ExceptionRegistry

To address the issue of managing commonly used exceptions across a codebase, we introduced the ExceptionRegistry. This class centralizes all available exceptions, making it easy to reference, import, and manage them from a single location.

Example

class ExceptionRegistry:
    """
    A centralized registry for managing custom exceptions used throughout the application.
    ...
    """
    PERMISSION_DENIED = ApiException(
        api_client_message="You do not have permission to access this resource.",
        status_code=403,
    )
    ALREADY_EXISTS = ApiException(
        api_client_message="The resource already exists.",
        status_code=409,
    )
    ...

Benefits

  • Centralization: All exceptions are defined in one place for easy management.
  • Reusability: Consistent use of exceptions across the entire application.
  • Improved Debugging: Clear, structured responses make debugging more efficient.

Summary

By combining the ApiException class and ExceptionRegistry, this approach simplifies exception management, ensures clear and consistent responses to users, and improves overall code maintainability. The result is a robust error-handling system tailored to the application's needs.

On this page