Search code examples
nestjsmulter

Change Unexpected field error message in NestJS


I have this code

@Post('files')
@UseInterceptors(FilesInterceptor("files", 5))
async uploadFiles () {
...
}

When I try to upload more files, I get this error “Unexpected field”, is there any way I can change this error to my custom one?


Solution

  • You can use Exception filters from NestJS like explained in the NestJS doc : Exception Filter NestJS doc

    create file like this http-exception.filter.ts

    import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
    import { Request, Response } from 'express';
    
    @Catch(HttpException)
    export class HttpExceptionFilter implements ExceptionFilter {
      catch(exception: HttpException, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        const request = ctx.getRequest<Request>();
        const status = exception.getStatus();
    
        response
          .status(status)
          .json({
            statusCode: status,
            timestamp: new Date().toISOString(),
            path: request.url,
          });
      }
    } 
    

    and use it like this in the controller

     @UseFilters(new HttpExceptionFilter())
     @UseInterceptors(FilesInterceptor('files', 5)
    

    then you can custom the logic of the filter to add your messages.