Guide on how to create a custom response using class-validator in NestJS

Is it feasible to customize the error response generated by class-validator in NestJs?

The default error message structure in NestJS looks like this:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": [
        {
            "target": {},
            "property": "username",
            "children": [],
            "constraints": {
                "maxLength": "username must be shorter than or equal to 20 characters",
                "minLength": "username must be longer than or equal to 4 characters",
                "isString": "username must be a string"
            }
        },
    ]
}

However, the external service interacting with my API requires a format closer to:

{
    "status": 400,
    "message": "Bad Request",
    "success": false,
    "meta": {
        "details": {
            "maxLength": "username must be shorter than or equal to 20 characters",
            "minLength": "username must be longer than or equal to 4 characters",
            "isString": "username must be a string"
        }
    }
}

Answer №1

Nestjs offers built-in elements known as Exception filters, which allow you to customize your response in case of exceptions. For more information, refer to the documentation available here.

If you are looking to create your own filter, the code snippet below can be a useful reference.

import { ExceptionFilter, Catch, ArgumentsHost, BadRequestException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(BadRequestException)
export class BadRequestExceptionFilter implements ExceptionFilter {
  catch(exception: BadRequestException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    response
      .status(status)
      // custom response manipulation can be done here
      .json({
        statusCode: status,
        timestamp: new Date().toISOString(),
        path: request.url,
      });
  }
}

Answer №2

When creating your own ValidationPipe, you have the option to include a custom exceptionFactory.

new ValidationPipe({
      exceptionFactory: (errors) =>  new HttpException({ error: "BAD_REQUEST" }, 400)
})

The expected type for the first argument is a string, but it can also accept an object. As stated in the NestJS documentation:

If you want to customize only the message part of the JSON response body, provide a string in the response argument. If you wish to fully customize the JSON response body, pass an object as the response argument. Nest will serialize the object and return it as the JSON response body.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating through JSON data to retrieve specific values and executing repetitive actions

When the form is submitted, I am making an AJAX request to PHP code and this is the response I receive. var data = { "empty":{ "game_sais_no":"Season cannot contain empty value", "game_sc_no":"Category cannot contain empty value", ...

Troubleshooting the issue with the AWS CodeBuild SAM esbuild integration not functioning

I currently have a Lambda's API Gateway repository in CodeCommit that I successfully build using esbuild with CLI (SAM BUILD and then SAM DEPLOY). Now, I am looking to streamline the building process by integrating it with CodePipeline. I started exp ...

Issue with AngularJS: Local storage not saving updated contenteditable data

My local storage implementation stops working when I attempt to incorporate contentEditable feature. Here is the link to the CodePen for reference: https://codepen.io/zanderbush/pen/WNwWbWe. Any assistance would be greatly appreciated. The functionality w ...

After the state loads in Ui-router, how can I execute a function?

Transitioning from jQuery to Angular, I am struggling with ui-router and states. In jQuery, I can make an AJAX call and then run another function on success. How can this be achieved in Angular? For instance, consider the code snippet below: var ivApp = ...

Issue: The object is unable to be executed as a function, resulting in the failure to return an array

Currently, I am extracting table values from the UI row by row. This involves clicking on each row and retrieving the corresponding data. exports.getTableData = function(callback){     var uiArray =[];     var count;         aLib.loadCheck(c ...

Problem encountered when attempting to use 'delete' as a property name

I am currently encountering an issue with a form that deletes a gallery from a database. Previously, the code was functioning properly but after some recent updates such as switching from jquery.interface to jquery-ui, I am now facing difficulties. Wheneve ...

What sets apart the process of installing AngularJS and AngularJS Core using NuGet?

I am curious about the difference between these two packages in my packages.config file. Would it be advisable to uninstall one of them? <?xml version="1.0" encoding="utf-8"?> <packages> <package id="angularjs" version="1.3.15" targetFr ...

Executing jQuery AJAX with PHP using 'POST' method to receive and process PHP code

Something seems to have gone wrong with my setup; it was functioning properly before but is now encountering issues. When trying to make a POST call from an HTML file to a php file (which fetches data from a REST API), instead of receiving the expected API ...

The PHP application encountered an error when trying to use an object of the mysqli_result type as an array

In my section, I have a straightforward display of data sourced from the database. Upon clicking options like construction and selecting countries like Algeria, the displayed values are [251, 211,712]. Similarly, for selections like Power in Egypt, the ou ...

Text field value dynamically changes on key press update

I am currently working on the following code snippet: {% for item in app.session.get('aBasket') %} <input id="product_quantity_{{ item['product_id'] }}" class="form-control quantity" type="text" value="{{ item['product_quan ...

Allowing Angular2 Components and their Sub Components to access a shared instance of ngModel within a service

Currently, I have been working on constructing a complex view that requires multiple functionalities. To ensure proper organization, I have divided it into various custom components. I don't want to go into great detail, but I have managed to make it ...

Jquery validation is ineffective when it fails to validate

I have implemented real-time jQuery validation for names. It functions correctly in real-time, however, when I attempt to submit the form, it still submits the value even after displaying an error message. Below is the code snippet for the validation: $ ...

Retrieving JSON information stored in a JavaScript variable

I'm feeling a bit embarrassed to admit it, but I am still learning the ropes when it comes to Javascript development. I've hit a roadblock and could really use some help from the experts here. Thank you in advance for all the assistance this comm ...

Retrieve the radio button value without using a key when submitting a form in JSON

Looking to extract the value upon form submission in Angular, here is the code: In my Typescript: constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, public formBuilder: FormBuilder, public alertCtrl ...

Having trouble transmitting data from the View to the Controller

Need help with this issue. I'm having trouble passing my data to the controller. Below is my ajax code. <script type="text/javascript"> $(document).on("click", "#login_button", function () { var userName = document.getElementById(" ...

The JSP AJAX response comes back empty

I am encountering an issue where I am using JQuery Ajax to call a REST API in JSP, but it keeps returning null no matter how I try. Strangely enough, the same code works when used in HTML. I have been searching online for a solution but haven't found ...

Vue/Vite vanilla setup encountering a 'Failed to fetch dynamically imported module' TypeError

We're currently working with a vanilla Vue/Vite setup and I'm encountering the error message TypeError: Failed to fetch dynamically imported module in Sentry logs. It appears that these errors coincide with new deployments to production, but I d ...

Difficulty encountered when attempting to utilize keyup functionality on input-groups that are added dynamically

I've exhausted all available questions on this topic and attempted every solution, but my keyup function remains unresponsive. $(document).ready(function() { $(document).on('keyup', '.pollOption', function() { var empty = ...

Display Nvd3 Pie Chart percentages in decimal format

I have integrated Nvd3 into my Angular project to create various types of charts. Utilizing the angular directive from Krispo's website, I am currently working on a pie chart that displays values in percentages. However, the displayed values are round ...

Guide on implementing two submission options in an HTML form using JavaScript

Currently, I am working on a form that includes two buttons for saving inputted data to different locations. However, I am facing an issue with the functionality of the form when it comes to submitting the data. Since only one submit function can be activa ...