Closed ymoreiratiti closed 4 years ago
You can use Exception Filters
In a Nest.js application, when you encounter a database error like a duplicate key violation while trying to add a new user with an existing email, you can catch this error and handle it appropriately. Assuming you're using an ORM like TypeORM, you can catch the QueryFailedError specifically for PostgreSQL databases.
Here's how you can handle the duplicate key violation error in your service or controller:
import { Injectable, UnprocessableEntityException} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, QueryFailedError } from 'typeorm';
import { CreateUserDto } from './dto/create-user.dto';
import { User } from './user.entity';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
) {}
async createUser(createUserDto: CreateUserDto): Promise<User> {
try {
return await this.userRepository.save(createUserDto);
} catch (error) {
if (error instanceof QueryFailedError && error.message.includes('duplicate key value violates unique constraint')) {
// Handle the duplicate key violation error
throw new UnprocessableEntityException('Email already exists');
} else {
// For other types of errors, rethrow or handle them as needed
throw error;
}
}
}
}
Hi.
My entity has a column with unique values. When i try to insert the same value, the api return "500 - Internal Server Error".
How can i catch and treat this response to anything more friendly? (Like an error "422 - Email already exists")
usuario.entity.ts
Return on shell