Skip to content

Commit

Permalink
fix(errors): improve error handling at start
Browse files Browse the repository at this point in the history
  • Loading branch information
josselinbuils committed Sep 1, 2023
1 parent e2919fe commit 4506404
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
7 changes: 6 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ Promise.all([import('@/core/services/logger'), import('./start')]).then(
}
process.on('uncaughtException', errorHandler);
process.on('unhandledRejection', errorHandler);
await start();
try {
await start();
} catch (error) {
logger.error(error);
process.exit(1);
}
}
);
16 changes: 13 additions & 3 deletions src/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { router } from './router';
const PORT = 3000;

export async function start(): Promise<() => Promise<void>> {
return new Promise((resolve) => {
return new Promise((resolve, reject) => {
const app = express();

const verify = (req: Request, res: Response, buffer: Buffer) => {
Expand All @@ -39,9 +39,19 @@ export async function start(): Promise<() => Promise<void>> {
app.use(errorMiddleware);

const server = app.listen(PORT, async () => {
try {
await connectToDatabase();
} catch (error) {
reject(
new Error(
`Unable to connect to the database: ${
(error as Error).stack ?? error
}`
)
);
return;
}
logger.info(`Homer started on port ${PORT}.`);
await connectToDatabase();
logger.info('Homer connected to the database.');
resolve(
async () =>
new Promise((r) => {
Expand Down

0 comments on commit 4506404

Please sign in to comment.