How do you handle different types of exceptions (e.g., `HttpException`, `Error`) within a single global `ExceptionsFilter`?

Responsive Ad Header

Question

Grade: Education Subject: Support
How do you handle different types of exceptions (e.g., `HttpException`, `Error`) within a single global `ExceptionsFilter`?
Asked by:
123 Viewed 123 Answers

Answer (123)

Best Answer
(572)
Inside the `catch` method of your global `ExceptionsFilter`, you can use `instanceof` checks to differentiate between exception types. For `HttpException` (or its subclasses like `BadRequestException`, `NotFoundException`), you can extract its status code and response object directly. For generic `Error` objects or unknown exceptions, you can default to an internal server error status (500) and provide a generic message, potentially logging the full error for debugging without exposing it to the client. This allows for tailored responses based on the error's origin.