Nestjs catch 500 error and return the error

Viewed 9002

When an unhandled error occurs, the front side gets a 500 error without any information about the error. It just receives this:

{
  "statusCode": 500,
  "message": "Internal server error"
}

But when I check the console, I see what happened and what the error message is. It's ok in the development environment but it's hard to figure out in production. How can I return a complete error message in production instead of just a simple message like "Internal server error"?

3 Answers

Generally you should be doing error handling around things that have a chance to go wrong (database operations, sending emails, validations), but if you're looking for a general error handling mechanism, you can use the Exception Filters construct that Nest provides to catch errors and manage them as necessary.

NestJS has the NotFoundException you can use.

You can implement your own custom Exception filters and add it to your controllers to capture a NotFoundException or whatever communication protocol, but this is assuming that you have an HTTP communication protocol.

So if http is the only communication protocol you are dealing with then you can just write this into one of your methods inside your service:

if (!user) {
  throw new NotFoundException('user not found');
}

And you would import that from:

import { Injectable, NotFoundException } from '@nestjs/common';

Finally found the answer to this question - you don't need any complicated exception filters, or interceptors, etc. You just need to wrap the code which is causing the 500 in an if statement, and throw a HttpException - note, throwing an Error will not work.

In other words, you need to resolve this error in your service class, not in your controller.

For example, in your service class:

  async getUsers(){
    let response = doSomething();
    if (response.status !== 200) {
      throw new HttpException(
        `Error getting users: ${response.status} ${response.statusText}`,
        response.status,
      )
    } else {
      return response.data
    }
  }
Related