Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a custom response from the class-validator in NestJS

Is it possible to return a custom error response from class-validator inside of NestJs.

NestJS currently returns an error message 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 service that consumes my API needs something more akin 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"
        }
    }
}
like image 868
Kinetic Avatar asked Sep 06 '19 10:09

Kinetic


1 Answers

Nestjs has built-in compoments named Exception filters, if you want to decorate your response in case of exceptions. You can find the relevant documentations here.

The following snippet could be helpful for writing your own filter.

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)
      // you can manipulate the response here
      .json({
        statusCode: status,
        timestamp: new Date().toISOString(),
        path: request.url,
      });
  }
}
like image 128
csakbalint Avatar answered Sep 17 '22 02:09

csakbalint