Login Sign Up
Advert
Your ad spot
Reserve this exclusive slot for the selected period.
Buy advertising →
Telegram community logo - Node.js Recipes
Added 14 Jul 2024

Node.js Recipes

@node_recipes
Number of subscribers: 3 153
Photos: 173
Videos: 7
Links: 610
Description:
You can view and join @node_recipes right away.
Source

Node.js Recipes | Сьогодні хочу поділитися підходом до обробки помилок бази даних у Nest...

Telegram community logo - Node.js Recipes Node.js Recipes @node_recipes
2 390 Views/Reach 2025-11-03 06:25 Message №882
Сьогодні хочу поділитися підходом до обробки помилок бази даних у Nest.js за допомогою Exception Filter.Ключові моменти:1. Перевірка бізнес-логіки на рівні БД – використання UNIQ/CHECK-обмежень у схемі бази даних.2. Робота з кодами помилок драйвера – наприклад, обробка стандартних кодів PostgreSQL (23505, 23514, 40001 тощо).3. Транзакції через typeorm-transactional – оскільки транзакції через @Transaction, фільтр є єдиним місцем, де можна перехопити помилку на рівні запиту.Приклад фільтра, щоб проілюструвати ідею:import type { ArgumentsHost, ExceptionFilter } from '@nestjs/common';import { Catch } from '@nestjs/common';import { Response } from 'express';import { DatabaseError } from 'pg';import { QueryFailedError } from 'typeorm';@Catch(QueryFailedError)export class TypeormExceptionFilter implements ExceptionFilter { catch(exception: QueryFailedError, host: ArgumentsHost) { const context = host.switchToHttp(); const response = context.getResponse<Response>(); if (exception.driverError instanceof DatabaseError) { if (exception.driverError.code === '40001') { return response.status(409).send({ message: 'Conflict. Please try again later.', }); } if (exception.driverError.code === '23505') { return response.status(400).send({ message: 'Should be unique', }); } if (exception.driverError.code === '23514') { switch (exception.driverError.constraint) { case 'not_negative_balance_check': { return response.status(400).send({ message: 'Not enough balance', }); } //… } } } throw exception; }} PS Цей метод не скасовує, а доповнює моніторинг журналу помилок вашої бази даних.