Skip to content

Commit 8d6a3d4

Browse files
committed
feat: production server error handling
1 parent 1b3a537 commit 8d6a3d4

1 file changed

Lines changed: 62 additions & 7 deletions

File tree

server.js

Lines changed: 62 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,69 @@
11
import 'dotenv/config';
2+
import http from 'http';
23
import app from './src/app.js';
34
import connectDB from './src/config/db.js';
5+
import { start } from 'repl';
46

57
const PORT = process.env.PORT || 5000;
8+
const NODE_ENV = process.env.NODE_ENV || 'development';
69

7-
connectDB().then(() => {
8-
app.listen(PORT, () => {
9-
console.log(`Server running on port ${PORT}`);
10-
console.log("Deployment");
11-
});
12-
}).catch((error) => {
13-
console.log(`Error: ${error}`);
10+
let server;
11+
12+
const startServer = async() => {
13+
try {
14+
if (!process.env.MONGO_URI) {
15+
throw new Error("MONGO_URI is missing in environment variables");
16+
}
17+
18+
if (!process.env.JWT_SECRET) {
19+
throw new Error("JWT_SECRET is missing in environment variables");
20+
}
21+
22+
await connectDB();
23+
console.log("DB connected successfully");
24+
25+
server = http.createServer(app);
26+
27+
server.listen(PORT, () => {
28+
console.log(`Server running in ${NODE_ENV} mode on port ${PORT}`);
29+
});
30+
} catch(error) {
31+
console.error("Startup error: ", error.message);
32+
process.exit(1);
33+
}
34+
};
35+
36+
startServer();
37+
38+
process.on("unhandledRejection", (err) => {
39+
console.error("Unhandled Rejection: ", err);
40+
shutdownGracefully();
1441
});
42+
43+
process.on("uncaughtException", (err) => {
44+
console.error("Uncaught Exception: ", err);
45+
shutdownGracefully();
46+
});
47+
48+
const shutdownGracefully = () => {
49+
if (server) {
50+
server.close(() => {
51+
console.log("Server closed grecefully");
52+
process.exit(1);
53+
});
54+
}
55+
else {
56+
process.exit(1);
57+
}
58+
};
59+
60+
process.on("SIGTERM", () => {
61+
console.log("SIGTERM received. Shutting down...");
62+
shutdownGracefully();
63+
});
64+
65+
process.on("SIGINT", () => {
66+
console.log("SIGINT reveiced. Shutting down...");
67+
shutdownGracefully();
68+
});
69+

0 commit comments

Comments
 (0)