Bird
0
0

Identify the error in this file validation pipe code:

medium📝 Debug Q14 of 15
NestJS - Pipes
Identify the error in this file validation pipe code:
export class FileValidationPipe implements PipeTransform {
  transform(file: Express.Multer.File) {
    if (!file) throw new BadRequestException('File is required');
    if (file.mimetype !== 'image/png' || file.mimetype !== 'image/jpeg') {
      throw new BadRequestException('Invalid file type');
    }
    return file;
  }
}
AThe mimetype check always throws because of incorrect logical operator
BThe file presence check is missing
CThe pipe does not return the file
DThe exception type is incorrect
Step-by-Step Solution
Solution:
  1. Step 1: Examine the mimetype condition

    The condition uses || (OR) between two checks: file.mimetype !== 'image/png' OR file.mimetype !== 'image/jpeg'.
  2. Step 2: Understand why this always triggers

    Because a file cannot be both 'image/png' and 'image/jpeg' at the same time, one of these will always be true, causing the exception every time.
  3. Final Answer:

    The mimetype check always throws because of incorrect logical operator -> Option A
  4. Quick Check:

    Use AND (&&) to check mimetype correctly [OK]
Quick Trick: Use && to check if mimetype is neither png nor jpeg [OK]
Common Mistakes:
  • Using || instead of && in mimetype checks
  • Forgetting to return the file after validation
  • Throwing wrong exception types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes