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

Typescript counterpart of a collection of key-value pairs with string keys and string values

Within the API I'm currently working with, the response utilizes a data type of List<KeyValuePair<string, string>> in C#. The structure appears as shown below: "MetaData": [ { "key": "Name", &q ...

Utilizing classes as types in TypeScript

Why is it possible to use a class as a type in TypeScript, like word: Word in the provided code snippet? class Dict { private words: Words = {}; // I am curious about this specific line add(word: Word) { if (!this.words[word.term]) { this.wor ...

React Material-UI is notorious for its sluggish performance

I recently started using React Material-ui for the first time. Whenever I run yarn start in my react app, it takes quite a while (approximately 25 seconds) on my setup with an i5 8400 + 16 GB RAM. Initially, I suspected that the delay might be caused by e ...

Unable to incorporate node-vibrant into Angular 7 project

Currently facing some challenges while attempting to integrate node-vibrant into my Angular 7 project: -Successfully imported with import * as Vibrant from 'node-vibrant';, but encountering a warning in VS Code: Module '"/Users/xxxx/Docume ...

Using TypeScript to return an empty promise with specified types

Here is my function signature: const getJobsForDate = async (selectedDate: string): Promise<Job[]> I retrieve the data from the database and return a promise. If the parameter selectedDate === "", I aim to return an empty Promise<Job[] ...

Navigating through the concept of passing objects by reference in child components of Angular 2+

Understanding that TypeScript uses object passing by reference can be challenging, especially when dealing with deep copy issues. This becomes particularly cumbersome when working within a theme. I recently encountered an issue with a component containing ...

The .ts source file is mysteriously missing from the development tool's view after being deployed

When I work locally, I can see the .ts source files, but once I deploy them, they are not visible in any environment. Despite setting my sourcemap to true and configuring browserTargets for serve, it still doesn't work. Can someone help with this issu ...

Error message "Potential Undefined Object" detected on a variable that is not an object in React with TypeScript

After finding and addressing the other 5-6 questions, I managed to partially fix it by using the "!" operator. Please do not remove this question for duplication purposes. However, what baffles me is that the variable is not recognized as an object. Here i ...

Compiling fails when creating an object literal with a generic key

I am attempting to accomplish the following task. function createRecord<T extends string>(key: T) : Record<T, T> { return {[key]: key}; // Type '{ [x: string]: T; }' is not assignable to type 'Record<T, T>' } Howe ...

Is it possible to customize the color of the placeholder and clear-icon in the ion-search bar without affecting

I am working with two ion-search bars and I need to customize the placeholder and clear icon color for just one of them. <ion-searchbar class="search-bar" placeholder="search"></ion-searchbar> My goal is to target a specific i ...

Incorrect deduction of the argument type for a higher-order function

If I wanted to create a function that takes an object of type T and another value, where the type P should somehow be restricted by T (for example, P should be an array of keys of T), I could easily write it like this: function customFunction<T, P exte ...

Debugging a node.js application remotely using SAP Cloud Foundry

Having successfully deployed multiple node.js express services on SAP Cloud Foundry, we have encountered a roadblock in the form of remote debugging. Recognizing that others may be facing similar challenges, we are putting forth a direct inquiry: What is ...

Using Rxjs to dynamically map values from an array with forkJoin

Greetings! I have a collection of Boolean observables and would like to apply a logical AND operation. Currently, I am passing static values 'a' and 'b', but I am unsure of the number of elements in the totalKeys array. import { forkJoi ...

Unable to reach the margin-left properties of the elements

I am facing an issue in accessing the current margin-left CSS property of the class .circle in the code snippet below. A demonstration of this problem can be found on a website called PLUNKr. The reason I need to access this property is because I have to ...

Updates to TypeScript 2.3.1 creating disruptions in SystemJS plunk

Check out this official Angular + TypeScript plunk using SystemJS 0.19.31, now updated to TypeScript 2.3.0. However, changing the SystemJS configuration in the same plunk to TypeScript 2.3.1 or 2.3.2 'typescript': 'npm:<a href="/cdn-cgi ...

The React Component in Next.js does not come equipped with CSS Module functionality

I have been attempting to incorporate and apply CSS styles from a module to a React component, but the styles are not being applied, and the CSS is not being included at all. Here is the current code snippet: ./components/Toolbar.tsx import styles from & ...

Is it possible to access the generic type that a different generic type inherits in TypeScript?

I've developed an interface specifically designed for types capable of self-converting to IDBKey: interface IDBValidKeyConvertible<TConvertedDBValidKey extends IDBValidKey> { convertToIDBValidKey: () => TConvertedDBValidKey; } My goal n ...

Utilizing TypeScript to define the parameter of a method within a generic interface by extracting a value from the generic type

In search of defining a versatile interface that can manage any Data type, I came up with an idea. This interface includes a dataKey property which simply holds a value of keyof Data. Additionally, it features a handler function where the parameter type sh ...

How can I add a new key value pair to an existing object in Angular?

I'm looking to add a new key value pair to an existing object without declaring it inside the initial object declaration. I attempted the code below, but encountered the following error: Property 'specialty' does not exist on type saveFor ...

In Angular, the object may be null

click here for image Encountering an error message stating that Object is possibly 'null' when utilizing querySelector and addEventListener in Angular. ...