-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.js
34 lines (29 loc) · 1.01 KB
/
test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const express = require('express');
const asyncHandler = require('express-async-handler');
const app = express();
// Simulate fetching user data from a database (asynchronous operation)
async function fetchUserData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const user = { id: 1, name: 'John Doe' };
// Simulate an error
reject(new Error('Database error'));
// resolve(user);
}, 1000);
});
}
// Using express-async-handler to handle asynchronous code
app.get('/user/:id', asyncHandler(async (req, res) => {
const userId = parseInt(req.params.id, 10);
const user = await fetchUserData(userId);
res.json(user);
}));
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.json({ title: 'Server Error', message: err.message, stackTrace: err.stack });
});
const PORT = process.env.PORT || 3003;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});