Errors from NestJS microservice class validator are visible in the docker container but do not appear in the API response

Seeking assistance with displaying validation errors in my NestJS project using class validator.

This is my first time working with microservices and NestJS, as it's for a school project. Errors from my 'user' microservice container are not appearing in the API response. How can I rectify this issue?

Below is a snippet from my main.ts:

  app.useGlobalPipes(new ValidationPipe({
    transform: true,
    validationError: { target: false, value: false },
    exceptionFactory: (validationErrors: ValidationError[] = []) => {
      return new RpcException(validationErrors);
    },
  }));

Here is a glimpse of my validation class user.dto.ts:

import {
  IsString,
  IsEmail,
  MinLength,
  IsEnum,
  IsOptional,
} from 'class-validator';
import { EnumRole } from '@lib/types/User';

export class UserDto {
  @IsEmail()
  email: string;

  @IsString()
  @MinLength(6)
  password: string;

  @IsEnum(EnumRole)
  @IsOptional()
  role: EnumRole;
}

Part of my user.service.ts for registering users:

  async registerUser(userDto: UserDto) {
    
    const hashedPassword = this.auth.send(
      AuthMessage.HASH_PASSWORD,
      userDto.password,
    );

    userDto.password = await firstValueFrom(hashedPassword);
    userDto.role = EnumRole.USER;

    const user = userDto as User;

    try {
      const newUser = await this.prisma.user.create({
        data: user as UserSchema,
      });

      return formatUser(newUser) as User;
    } catch (e) {
      if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') { 
        return 'Email already exists';
      }
    }
  }

A sample JSON sent to my API:

{
    "email" : "4",
    "password" : "pass"
}

Validation occurs successfully in the container, but the error response in postman shows:

{
  "statusCode": 500,
  "message": "Internal server error"
}

I'm providing detailed code snippets for better understanding. Any guidance on resolving this issue would be appreciated.

Thank you for your support!

Answer №1

When the microservice returns an RpcException, it gets serialized into an Error within the microservice gateway. This results in the HTTP server displaying an Internal Server Error because Nest automatically interprets plain Error instances as HTTP 500 errors. To return a different status code such as 400, you need to catch the error from the microservice and translate it into the appropriate HTTP exception that Nest can recognize.

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

Adjusting the background opacity when the sidebar is open in a React + Typescript project

I am currently working on customizing a sidebar using the react-pro-sidebar library along with React and Typescript. The sidebar layout seems to be in order, but I am facing difficulty in adjusting the background color of the rest of the screen when the si ...

Is it advisable to include auto-generated files in an npm package upon publication?

I have a TypeScript NPM package where my build process compiles all *.ts files into myLib.d.ts, myLib.js, and myLib.js.map. In order for my NPM package to function properly, it requires the src/*.ts files as well as the auto-generated myLib.* files. Howe ...

What could be causing these Typescript compilation errors I am experiencing?

I am puzzled by the appearance of these errors, especially since I copied the entire ClientApp folder from a running application where they did not exist. https://i.sstatic.net/tcO5S.png Here is the structure of my project: https://i.sstatic.net/P4Ntm.p ...

Add a service to populate the values in the environment.ts configuration file

My angular service is called clientAppSettings.service.ts. It retrieves configuration values from a json file on the backend named appsettings.json. I need to inject this angular service in order to populate the values in the environment.ts file. Specific ...

Ways to decrease the size of this item while maintaining its child components?

Here is an object that I am working with: { "name": "A", "children": [ { "name": "B", "open": false, "registry": true, "children": [ { ...

What's Going on with My Angular Dropdown Menu?

Snippet of HTML code: <li class="nav-item dropdown pe-3"> <a class="nav-link nav-profile d-flex align-items-center pe-0" (click)="toggleProfileMenu()"> <img src="assets/img/profile-img.jpg" alt=& ...

What causes npm start to fail in Angular 6 after incorporating social login functionality?

I am currently working on integrating Social Login functionality into my app. I have attempted to incorporate the following: npm install --save angular-6-social-login-fixed npm install --save angular-6-social-login npm install --save angular-6-social-log ...

Troubleshooting problems encountered when duplicating an array in JavaScript

I am attempting to utilize properties and flatmap to modify an array without altering the original data. I have implemented this method in two different instances within a single dispatch call in Vue.js when transferring data from parent to children comp ...

What's the trick to inserting a "dot" beneath a DatePicker?

Could someone assist me in adding a small "dot" below certain dates on MUIX DatePicker, similar to the example shown here? Thank you. ...

Capturing user audio on the client side with Angular

Is there a built-in feature in Angular to record client-side audio input? I have attempted using the p5 library, but it is encountering integration problems. ...

react-data-grid: The type of createElement is found to be invalid when using typescript and webpack externals

Hello everyone, I'm currently facing a challenge with setting both the react-data-grid and react-data-grid-addons libraries as externals in webpack to prevent them from being included in my asset bundling. Everything was working perfectly until I move ...

Debugging a Python 2.7 application in a Docker container with Python 3 is easily done using Visual Studio Code

I am encountering an issue while trying to debug my application within a docker container. The application is coded in Python 2.7, but VS Code is attempting to debug it using Python 3 which leads to package resolution problems and exceptions being thrown. ...

Using ReactJS with Typescript: attempting to interpret a value as a type error is encountered (TS2749)

Currently, I am working on coding a ReactJS class using Typescript and Material-ui in a .tsx file. In one of the custom components that I have created, I need to establish a reference to another component used within this custom component. export class My ...

How come the path alias I defined is not being recognized?

Summary: I am encountering error TS2307 while trying to import a file using an alias path configured in tsconfig.json, despite believing the path is correct. The structure of directories in my Angular/nx/TypeScript project appears as follows: project |- ...

Troubleshooting an Integration Problem Between Express and socket.io

Having trouble reaching the io.on('connect') callback in my basic express setup. The connection seems to stall. Node 12.14.1 express 4.17.1 socket.io 3.0.1 code import express, { ErrorRequestHandler } from 'express'; import path from ...

Utilizing a class structure to organize express.Router?

I've been playing around with using Express router and classes in Typescript to organize my routes. This is the approach I've taken so far. In the index.ts file, I'm trying to reference the Notes class from the notes.ts file, which has an en ...

The 'ngForOf' directive cannot be bound to 'div' element as it is not recognized as a valid property

Encountering an issue with adding an ngFor directive on a div, which is causing a warning and preventing my HTML from rendering properly. I experimented with using *ngFor on various elements like <li>, <tr>, and <span>, but kept getting ...

Choosing everything with ngrx/entity results in not selecting anything

Issue with Selector I am facing an issue with my selector in the component. Despite making the call, the component does not update with books from the FakeApiService. The actions and effects seem to be functioning correctly. The problem seems to be relat ...

"Adjusting the size of a circle to zero in a D3 SVG using Angular 2

Trying to create a basic line graph using d3 in Angular 2 typescript. Below is the code snippet: import { Component, ViewChild, ElementRef, Input, OnInit } from '@angular/core'; import * as d3 from 'd3'; @Component({ selector: 'm ...

What causes an interface to lose its characteristics when a property is defined using index signatures?

Here's the code snippet I'm having trouble with, which involves tRPC and Zod. import { initTRPC, inferRouterOutputs } from '@trpc/server'; import { z } from "zod"; const t = initTRPC.create(); const { router, procedure } = t; ...