Overview
Understanding how to manipulate response status codes in NestJS can be crucial for creating an informative API. This tutorial shows how to set custom status codes across various situations in your NestJS application.
Basic Response Override
Setting a custom status code in NestJS can be done simply by importing and using the @HttpCode()
decorator.
import { Controller, Post, HttpCode } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Post()
@HttpCode(204)
create() {
return 'This action adds a new cat.';
}
}
This will override the default status code (201 for POST requests) to 204, indicating that the request was successful but there’s no content to be sent back as a response.
Using status()
Within a Service
Sometimes, setting a static status code is not sufficient, and you may need to set it dynamically. This can be done by injecting the Response
object into your service.
import { Injectable, Req, Res } from '@nestjs/common';
import { Response } from 'express';
@Injectable()
export class CatsService {
createCat(@Req() request: Request, @Res() response: Response) {
// Your logic here
response.status(202).send('Cat is being created.');
}
}
This allows you to set any status code depending on your application logic.
Exception Filters for Error Handling
Setting custom error status codes is often achieved using exception filters. You can create your own Exception that extends HttpException
.
import { HttpException, HttpStatus } from '@nestjs/common';
export class CatNotFoundException extends HttpException {
constructor() {
super('Cat not found', HttpStatus.NOT_FOUND);
}
}
To throw this exception use:
import { Injectable } from '@nestjs/common';
@Injectable()
export class CatsService {
findCat(catId: string) {
// Logic to find the cat
throw new CatNotFoundException();
}
}
Advanced HTTP Response with ApiResponse
Decorator
The @ApiResponse
decorator from the @nestjs/swagger
package allows fine-grained control over response status code and Swagger documentation.
import { Controller, Post, Body } from '@nestjs/common';
import { ApiResponse, ApiOperation } from '@nestjs/swagger';
@Controller('cats')
export class CatsController {
@Post()
@ApiOperation({ summary: 'Create cat' })
@ApiResponse({ status: 201, description: 'The record has been successfully created.'})
@ApiResponse({ status: 403, description: 'Forbidden.'})
create(@Body() createCatDto: CreateCatDto) {
// Your logic here
return this.catsService.create(catDto);
}
}
This approach not only handles response statuses but also assists with API documentation generation.
Conclusion
Setting custom status codes in NestJS allows better communication with front-end developers and clients who consume your API. Through decorators, response objects, and exception filters, NestJS offers versatile methods to manage status codes effectively. The chosen method depends on the use case, but a wise combination supports a robust and maintainable code architecture.