> ## Documentation Index
> Fetch the complete documentation index at: https://docs.erixcel.com/llms.txt
> Use this file to discover all available pages before exploring further.

# db-error.function.ts

Normaliza errores comunes de PostgreSQL. En concreto, transforma el código `23505` de restricción única en mensajes `BadRequestException`; los demás errores se vuelven a lanzar.

```typescript db-error.function.ts theme={null}
import { BadRequestException } from '@nestjs/common';
import { Trace } from 'traceflow';

export class DbErrorFunction {
  @Trace({ name: 'Procesar error de base de datos', type: 'method' })
  static handleDbError(error: any): never {
    // Check if it's a wrapper error with 'cause' (common in some setups) or the direct error
    const dbError = error.cause || error;

    if (dbError?.code === '23505') {
      const constraint = dbError?.constraint || '';
      const detail = dbError?.detail || '';

      if (constraint.includes('email') || detail.includes('email')) {
        throw new BadRequestException(['El correo electrónico ya está registrado']);
      }

      if (constraint.includes('dni') || detail.includes('dni')) {
        throw new BadRequestException(['El DNI ya está registrado']);
      }

      if (constraint.includes('phone') || detail.includes('phone')) {
        throw new BadRequestException(['El teléfono ya está registrado']);
      }

      throw new BadRequestException(['Ya existe un registro con estos datos']);
    }

    throw error;
  }
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.