Skip to content

Commit f93de71

Browse files
committed
refactor(app.ts): to handle errors and shutdowns, and update bot/index.ts to handle webhook requests and errors
1 parent e4c3aef commit f93de71

2 files changed

Lines changed: 76 additions & 11 deletions

File tree

src/app.ts

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,57 @@
11
import { CopBot } from './bot';
22
import { ServiceProvider } from './service/database/ServiceProvider';
33
import logger from './utils/logger';
4+
45
async function main() {
56
const cop = CopBot.getInstance();
6-
await ServiceProvider.initialize();
7-
logger.info('initialize Database');
8-
await cop.initial();
9-
logger.info('initial bot');
7+
try {
8+
await ServiceProvider.initialize();
9+
logger.info('Initialized Database');
10+
11+
await cop.initial();
12+
logger.info('Bot initialized');
13+
} catch (error: any) {
14+
logger.error('Error during initialization:', error);
15+
process.exit(1); // Exit if initialization fails
16+
}
17+
18+
// Handle graceful shutdown on SIGTERM
1019
process.on('SIGTERM', async () => {
1120
logger.info('SIGTERM signal received. Closing bot...');
1221
try {
1322
const db = ServiceProvider.getInstance();
14-
await db.close();
23+
await db.close(); // Ensure DB is closed before exiting
1524
logger.info('Database closed.');
1625
} catch (error: any) {
1726
logger.error('Error during shutdown:', error);
1827
} finally {
28+
logger.info('Shutting down bot process');
1929
process.exit(0);
2030
}
2131
});
32+
33+
// Handle unhandled promise rejections
2234
process.on('unhandledRejection', (reason, promise) => {
2335
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
36+
// Consider gracefully shutting down the app here if necessary
2437
});
2538

26-
process.on('uncaughtException', (error) => {
27-
console.error('Uncaught Exception:', error);
28-
process.exit(1);
39+
// Handle uncaught exceptions
40+
process.on('uncaughtException', async (error: any) => {
41+
logger.error('Uncaught Exception:', error);
42+
try {
43+
const db = ServiceProvider.getInstance();
44+
await db.close(); // Close DB before exiting on uncaught exception
45+
logger.info('Database closed due to uncaught exception.');
46+
} catch (shutdownError: any) {
47+
logger.error('Error during shutdown:', shutdownError);
48+
} finally {
49+
process.exit(1); // Exit the process on uncaught exception
50+
}
2951
});
3052
}
31-
main().catch((error) => console.error('Application error:', error));
53+
54+
main().catch((error) => {
55+
logger.error('Application error during startup:', error);
56+
process.exit(1); // Exit if the main function fails
57+
});

src/bot/index.ts

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,46 @@ export class CopBot {
3131
const web_hook = Config.web_hook;
3232
const isProduction = Config.environment === 'production';
3333
if (isProduction) {
34-
const server = http.createServer(webhookCallback(this._bot, 'http', { timeoutMilliseconds: 30000 }));
34+
const server = http.createServer(async (req, res) => {
35+
if (req.method === 'POST' && req.url === '/webhook') {
36+
let body = '';
37+
38+
// Collect data chunks
39+
req.on('data', (chunk) => {
40+
body += chunk;
41+
});
42+
43+
// Handle incoming request once the data is complete
44+
req.on('end', async () => {
45+
try {
46+
// Parse the incoming JSON body
47+
const update = JSON.parse(body);
48+
if (!update) {
49+
console.error('Received empty body or malformed JSON.');
50+
return (res.statusCode = 400);
51+
}
52+
53+
console.log('Received webhook body:', update);
54+
await this._bot.handleUpdate(update); // Handle the update
55+
res.statusCode = 200; // Success response to Telegram
56+
res.end();
57+
} catch (error: any) {
58+
console.error('Error parsing JSON in webhook request:', error.message || error.stack);
59+
res.statusCode = 500; // Internal Server Error
60+
res.end('Internal Server Error');
61+
}
62+
});
63+
64+
req.on('error', (err) => {
65+
console.error('Request error:', err);
66+
res.statusCode = 400;
67+
res.end('Bad Request');
68+
});
69+
} else {
70+
res.statusCode = 404; // Not Found
71+
res.end();
72+
}
73+
});
3574
server.listen(port, '0.0.0.0', () => {
3675
console.log(`Bot started on port ${port}`);
3776
});
@@ -44,7 +83,7 @@ export class CopBot {
4483
} else {
4584
console.log('No webhook set.');
4685
}
47-
} catch (error:any) {
86+
} catch (error: any) {
4887
console.error('Error setting webhook:', error.message || error.stack);
4988
process.exit(1); // Exit if critical error
5089
}

0 commit comments

Comments
 (0)