How to easily send JSON errors response for API routes in Nestjs?

February 18, 2023 - 3 min read

To easily send JSON error responses for API routes in Nestjs, you can use the HttpException class from the @nestjs/common module and throw a new exception instance using the throw keyword from either of the API Controllers or the Services class. The HttpException class accepts 2 arguments where the first argument should be the error message itself and the second argument should be the HTTP error status code.

TL;DR

// Controller class of the `/greet` `GET` API
import { Controller, Get, HttpException, HttpStatus } from "@nestjs/common";

@Controller("/greet")
export class GreetController {
  @Get()
  sayHello() {
    // using the `HttpException` class and passing the error message
    // as the first argument and the status code as the second argument
    // to make a JSON error response
    throw new HttpException("API is deprecated", HttpStatus.MOVED_PERMANENTLY);
  }
}

For example, let's say we have a GET API route called /greet and on requesting this API, we should give out an error response with the message called API is deprecated with an HTTP status code of 301 (MOVED PERMANENTLY).

To do that, first let's go into the Controllers class of the /greet API route, which is the GreetController class.

It looks like this,

Filepath: `src/greet/greet.controller.ts

// Controller class of the `/greet` `GET` API
import { Controller, Get } from "@nestjs/common";

@Controller("/greet")
export class GreetController {
  @Get()
  sayHello() {
    return "Hello World";
  }
}

As you can see from the above code the API will now return the string of Hello World on request.

We aim to throw an HttpException HTTP error with the message API is deprecated and with the status code of 301 (MOVED PERMANENTLY).

To do that, we can use the throw keyword followed by the new keyword, then the HttpException class. The first argument of the HttpException class is the message API is deprecated and the second argument is the HTTP status code.

For easy access to the HTTP status codes, we can use the HttpStatus object from the @nestjs/common module.

It can be done like this,

// Controller class of the `/greet` `GET` API
import { Controller, Get, HttpException, HttpStatus } from "@nestjs/common";

@Controller("/greet")
export class GreetController {
  @Get()
  sayHello() {
    // using the `HttpException` class and passing the error message
    // as the first argument and the status code as the second argument
    // to make a JSON error response
    throw new HttpException("API is deprecated", HttpStatus.MOVED_PERMANENTLY);
  }
}

Now if you request the /greet GET API, you will get a JSON response like this,

{
  "statusCode": 301,
  "message": "API is deprecated"
}

This proves that the error response functionality in the GreetController class is working as expected. Yay 🥳!

See the above code live in codesandbox.

That's all 😃.