How to handle errors in NestJS?

Member

by jermain , in category: JavaScript , a year ago

How to handle errors in NestJS?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by schuyler , a year ago

@jermain 

In NestJS, you can handle errors in a few different ways:

  1. Using try-catch blocks: You can use try-catch blocks in your code to catch and handle errors that occur during execution. For example:
1
2
3
4
5
try {
  // code that might throw an error
} catch (error) {
  // handle the error
}


  1. Using the @Catch() decorator: You can use the @Catch() decorator to create a global error handler for a specific type of error. For example:
1
2
3
4
5
6
@Catch(MyCustomError)
export class MyCustomErrorHandler implements ExceptionFilter {
  catch(exception: MyCustomError, host: ArgumentsHost) {
    // handle the error
  }
}


  1. Using the HttpException class: You can throw an instance of the HttpException class to return a specific HTTP status code and error message to the client. For example:
1
throw new HttpException('Invalid email', HttpStatus.BAD_REQUEST);


  1. Using the HttpStatus enum: You can use the HttpStatus enum to return a specific HTTP status code to the client. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@Controller()
export class AppController {
  @Get()
  getHello(): string {
    return 'Hello World!';
  }

  @Get('error')
  getError(): never {
    throw new HttpException('Something went wrong', HttpStatus.INTERNAL_SERVER_ERROR);
  }
}


I hope this helps! Let me know if you have any other questions.

Member

by emely , 4 months ago

@jermain 

Yes, that's correct! In addition to the mentioned methods, NestJS also provides a few more options to handle errors:


Using custom exception filters: You can create your own custom exception filters by extending the BaseExceptionFilter class or implementing the ExceptionFilter interface. These filters can be used to catch and handle specific types of exceptions, allowing you to customize the error response. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@Catch(MyCustomError)
export class MyCustomErrorHandler implements ExceptionFilter {
  catch(exception: MyCustomError, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse();
    response.status(HttpStatus.BAD_REQUEST).json({
      statusCode: HttpStatus.BAD_REQUEST,
      message: 'Custom error message',
    });
  }
}


Using built-in exception filters: NestJS provides some built-in exception filters that you can use to handle common types of exceptions, such as HttpExceptionFilter to handle HttpExceptions, AllExceptionsFilter to handle all uncaught exceptions, etc. These filters can be applied at the controller or global level to handle errors in a consistent way throughout your application.


Using pipes: Pipes allow you to transform and validate incoming data before it reaches your route handlers. You can use pipes to handle validation errors and other data-related errors.


Using interceptors: Interceptors allow you to intercept incoming requests and outgoing responses. You can use interceptors to handle errors before they reach the route handlers or modify the error response.


By implementing a custom exception handler: You can create a custom exception handler by implementing the ErrorHandler interface. This allows you to customize the error response or perform any other handling logic for exceptions.


These are some of the ways you can handle errors in NestJS. The choice depends on the specific requirements and complexity of your application.