Skip to content

Commit 024b9e1

Browse files
committed
async await error handling without try catch 🚀
1 parent df7677b commit 024b9e1

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

Asynchronous-JavaScript/byeTryCatchErrorHandling.js

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
// catchAwait.js
2-
const catchAwait = promise => (
2+
const catchAwait = promise =>
33
promise
44
.then(data => ({ data, error: null }))
5-
.catch(error => ({ error, data: null }))
6-
);
5+
.catch(error => ({ error, data: null }));
76

87
module.exports = catchAwait;
98

@@ -17,6 +16,31 @@ const allItems = async () => {
1716
// code
1817
}
1918
console.error(error);
20-
}
19+
};
2120

2221
allItems();
22+
23+
/**
24+
* Another way
25+
*/
26+
27+
// catchAsync.js
28+
module.exports = fn => {
29+
return (req, res, next) => {
30+
fn(req, res, next).catch(next);
31+
};
32+
};
33+
34+
// createOne.js
35+
36+
exports.createOne = Model =>
37+
catchAsync(async (req, res, next) => {
38+
const doc = await Model.create(req.body);
39+
40+
res.status(201).json({
41+
status: 'success',
42+
data: {
43+
data: doc,
44+
},
45+
});
46+
});

0 commit comments

Comments
 (0)