In your codebase, there’s a custom exception class RequestHttpException designed to manage errors in a structured and consistent manner across the application. When throwing exceptions, it’s mandatory to use RequestHttpException instead of the built-in exception classes from NestJS. This practice ensures that error handling remains consistent and informative throughout your application. Here’s how you should use RequestHttpException:
throw new RequestHttpException(
  {
    className: 'AuthenticationHelperService',  // The name of the class where the exception is thrown
    methodName: 'verifyAndGetUserInformationForType',  // The name of the method where the exception is thrown
    message: 'Email and password are required',  // A brief description of the error
    readableMessagePath: 'error.AUTH_INVALID_CREDENTIALS',  // The path to the error message in the i18n translation files
  },
  400,  // The HTTP status code
);

Arguments of RequestHttpException

  1. className: The name of the class where the exception is being thrown. This helps in identifying the source of the error.
  2. methodName: The name of the method where the exception is being thrown. This provides a clear context on where the error occurred.
  3. message: A brief description of the error, useful for logging and debugging purposes.
  4. readableMessagePath: The path to the error message in the i18n translation files, which allows for localized error messages. Whenever a new readable error message is introduced, ensure it’s also added to the i18n translation files under i18n/<language_code>/error.json.
  5. status: The HTTP status code which will be sent in the response.

Behind the Scenes

When an exception is thrown using RequestHttpException, the HttpExceptionFilter catches it as part of the global exception handling mechanism in NestJS. The filter does the following:
  1. Retrieves the current internationalization (i18n) context to provide localized error messages.
  2. Prepares a structured error response with details like the status code, where the error was generated, the description of the error, and a user-readable message.
  3. Optionally, if Sentry is configured, logs the exception for further analysis and debugging. This is handled by the SentryService injected into the HttpExceptionFilter.
  4. Sends the structured error response back to the client, adhering to the expected error response format of the application.
This mechanism ensures that all errors thrown in the application are handled in a uniform manner, making it easier to trace, debug, and resolve issues.