Skip to content

Commit cde8ef1

Browse files
committed
feat(decorator): add error handling decorator for methods
- Introduced `Catch` decorator to handle errors in methods with custom or default responses. - Logs the error with category and message details. - Sends error messages to users via Telegram context (if available).
1 parent 4990ff8 commit cde8ef1

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { Context } from 'grammy';
2+
import { ErrorResponse } from '../types/ResponseTypes';
3+
import logger from '../utils/logger';
4+
export function Catch(customResponse?: ErrorResponse) {
5+
return function (target: any, propKey: string, descriptor: PropertyDescriptor) {
6+
const originalMethod = descriptor.value;
7+
descriptor.value = async function (...args: any[]) {
8+
const ctx: Context = (this as any)?.ctx || args[0];
9+
try {
10+
return await originalMethod.apply(this, args);
11+
} catch (error: any) {
12+
// Custom response or default error message
13+
const errorResponse: ErrorResponse = customResponse || {
14+
message: error.message,
15+
statusCode: error.statusCode || 500,
16+
category: 'General',
17+
};
18+
logger.error(`[Category: ${errorResponse.category}] Error in ${target.constructor.name}.${propKey}(): ${error.message}`);
19+
// Send the error message to the user (if context is available)
20+
if (ctx && typeof ctx.reply === 'function') {
21+
await ctx.reply(errorResponse.message);
22+
}
23+
}
24+
};
25+
26+
return descriptor;
27+
};
28+
}

0 commit comments

Comments
 (0)