BE/src/utils/helper.ts

50 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-02-24 10:32:41 +05:30
import {
BadRequestException,
InternalServerErrorException,
Logger,
} from '@nestjs/common';
import * as oracledb from 'oracledb';
const logger = new Logger('Helper');
export const handleError = (error: any, context: string = 'UnknownService'): never => {
if (error instanceof BadRequestException) {
logger.warn(`[${context}] ${error.message}`);
throw error;
}
if (error.message?.includes('NJS-107')) {
logger.warn(`[${context}] Invalid cursor encountered: ${error.message}`);
throw new BadRequestException('Invalid database response.');
}
if (error.message?.includes('ORA-')) {
logger.error(`[${context}] Oracle error occurred: ${error.message}`);
throw new InternalServerErrorException(error.message);
}
logger.error(`[${context}] Unexpected error:`, error.stack || error);
throw new InternalServerErrorException(error.message || 'Internal error');
};
export const closeOracleDbConnection = async (connection: any, context: string = 'UnknownService'): Promise<void> => {
if (connection) {
try {
await connection.close();
} catch (closeErr) {
logger.error(`[${context}] Failed to close DB connection`, closeErr.stack || closeErr);
}
}
};
export const fetchCursor = async <T>(cursor: oracledb.ResultSet<T>, context: string = 'UnknownService'): Promise<T[]> => {
try {
const rows = await cursor.getRows();
await cursor.close();
return rows;
} catch (err) {
logger.error(`[${context}] Failed to fetch from cursor`, err.stack || err);
throw new InternalServerErrorException('Error reading data from database.');
}
};