Im using the async function inside the object to send a response in express.js
Controller Code :
module.exports = {
async signUpEmail(req, res) {
/**
* @description Parameters from body
* @param {string} firstName - First Name
* @inner
*/
const firstName = req.body.firstName;
res.send({ success: name });
throw new Error(); // purposely Done
}
}
Question:
Since the signUpEmail method is async in my case and it will get rejected with whatever my async method throw's here it's comes Error
.(purposely put there)
so getting this logged in the console.
(node:13537) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error
(node:13537) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
So i'm supposed to handle it from the routes from where i'm calling it.
Router Code
const routes = require('express').Router();
const SignUpController = require('../controllers/signUpController')
// /signup
routes.post('/', SignUpController.signUpEmail);
module.exports = routes;
some what like this SignUpController.signUpEmail().then(…);
But since i'm not calling function in the routes i'm just passing. How this can be done effectively ?
PS:Please Don't suggest too complicated solutions. I'm beginner with JS and is learning through.
I Didn't use chainable route handlers because i want to create modular, mountable route handler.
Official Doc Example
If an error condition arises inside a promise, you “reject” the promise by calling the reject() function with an error. To handle a promise rejection, you pass a callback to the catch() function.
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .
The unhandledrejection event is sent to the global scope of a script when a JavaScript Promise that has no rejection handler is rejected; typically, this is the window , but may also be a Worker . This is useful for debugging and for providing fallback error handling for unexpected situations.
Handling rejected promises You can handle rejected promises without a try block by chaining a catch() handler before awaiting the promise.
In your route, you will need to add a wrapper to catch thrown errors:
let wrapper = fn => (...args) => fn(...args).catch(args[2]);
// /signup
routes.post('/', wrapper(SignUpController.signUpEmail));
With this method you can use a top level error catcher and do not need to use internal try catch blocks in your routes, unless you need to them contextually.
Use error catching middleware to achieve this as follows:
// last middleware in chain
app.use(function(err, req, res, next) {
// handle your errors
});
Now in your routes you can throw errors and they will be caught by that middleware. I like to throw custom errors and handle their response and logging in this middleware.
Aside: The async await pattern is great for writing asynchronous code that is easy for a human to read in a synchronous fashion. Just remember that once you go async, you should stay async! Using a promisification library such as Bluebird and invoking .promisifyAll
on nodeback
libraries is highly recommended.
EDIT : Source - Asynchronous Error Handling in Express with Promises, Generators and ES7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With