|
1 | 1 | import { CopBot } from './bot'; |
2 | 2 | import { ServiceProvider } from './service/database/ServiceProvider'; |
3 | 3 | import logger from './utils/logger'; |
| 4 | + |
4 | 5 | async function main() { |
5 | 6 | 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 |
10 | 19 | process.on('SIGTERM', async () => { |
11 | 20 | logger.info('SIGTERM signal received. Closing bot...'); |
12 | 21 | try { |
13 | 22 | const db = ServiceProvider.getInstance(); |
14 | | - await db.close(); |
| 23 | + await db.close(); // Ensure DB is closed before exiting |
15 | 24 | logger.info('Database closed.'); |
16 | 25 | } catch (error: any) { |
17 | 26 | logger.error('Error during shutdown:', error); |
18 | 27 | } finally { |
| 28 | + logger.info('Shutting down bot process'); |
19 | 29 | process.exit(0); |
20 | 30 | } |
21 | 31 | }); |
| 32 | + |
| 33 | + // Handle unhandled promise rejections |
22 | 34 | process.on('unhandledRejection', (reason, promise) => { |
23 | 35 | console.error('Unhandled Rejection at:', promise, 'reason:', reason); |
| 36 | + // Consider gracefully shutting down the app here if necessary |
24 | 37 | }); |
25 | 38 |
|
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 | + } |
29 | 51 | }); |
30 | 52 | } |
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 | +}); |
0 commit comments