
NestJS Error Handling: Stop Sending Ugly 500 Errors to Your Users
One of the first things I do on any new NestJS project now is set up a global exception filter. Took me too long to make this a habit.
Without one, your error responses are inconsistent. A NotFoundException returns { statusCode, message, error }. An unexpected database error returns { statusCode, message } with no error field. A validation error returns { message: string[] } with an array instead of a string. Your frontend has to handle three different shapes just to display an error message.
A global exception filter fixes all of that in one place. You define the shape once, every error in the entire app goes through it, and the response always looks the same.
What confuses beginners is the difference between HttpException and a plain JavaScript Error. If you throw new Error('something') in a service, the filter can't extract a useful status code or message it just logs the stack trace and returns a 500. Always use NestJS's built-in exceptions (NotFoundException, BadRequestException, etc.) or you can also extend HttpException for custom ones.