0

I have app.useGlobalPipes(new ValidationPipe()); that works well for my schemas. API returns 400 and error messages.

The problem is when I pass incorrect data in sub schema:

@Schema({ _id: false })
class Question {
  @Prop({ required: true })
  text: string;

  @Prop({ required: true })
  correct: boolean;
}

const QuestionSchema = SchemaFactory.createForClass(Question);

export type QuizDocument = Quiz & Document & ITimestamp;

@Schema({ timestamps: true })
export class Quiz {
  @Prop({ required: true })
  name: string;

  @Prop({ required: true })
  description: string;

  @Prop()
  file: string;

  // THERE IS THE PROBLEM:
  @Prop({ required: true, type: [QuestionSchema] })
  questions: MongooseSchema.Types.Array;
}

export const QuizSchema = SchemaFactory.createForClass(Quiz);

In this case - for incorrect text and correct fields from QuestionSchema API returns 500.

wozniaklukasz
  • 141
  • 1
  • 12

1 Answers1

0

I'd say that is correct behavior.

ValidationPipe validates incoming requests, not mongo schema.

If you are getting 500 that means schema validation works you just need to deliver the error message properly.

One option is to use interceptor

@Injectable()
export class ExceptionInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      catchError((error) => {
        console.error({
          message: error.message,
          stack: error.stack,
          name: error.name,
        });

        switch (true) {
          case error instanceof HttpException:
            throw error;
          case error.name === 'MongoError':
            throw new UnprocessableEntityException(error.message);
          default:
            throw new InternalServerErrorException();
        }
      }),
    );
  }
}

and in your main.ts file include

app.useGlobalInterceptors(new ExceptionInterceptor());

You have other examples of filtering errors here

n1md7
  • 1,825
  • 1
  • 9
  • 18