Answer the question
In order to leave comments, you need to log in
Node.js (or other asynchronous frameworks): How to catch errors?
Here is a question. Maybe my stiff synchronous brain just doesn't see the solution that lies on the surface. But I don't understand how to handle errors with an asynchronous approach, how to issue a 500 page to the user. After all, how does the usual synchronous request work (schematically):
try {
responce = (function request(req) {
var user = auth.getUser(req);
if (user.auth) {
var data = db.getData();
if (data) {
return new Responce(template.render(data));
}
}
return error404;
})(req);
} catch(e) {
show500(e);
}
try {
(function request(req, res) {
auth.getUser(req, function(user) {
if ( ! user.auth) {
return res.error404();
}
db.getData(function(data) {
if ( ! data) {
return res.error404();
}
res.write(template.render(data));
});
});
})(req, res);
} catch(e) {
res.show500(e);
}
try {
(function request(req, res) {
auth.getUser(req, function(user) {
try {
if ( ! user.auth) {
return res.error404();
}
db.getData(function(data) {
try {
if ( ! data) {
return res.error404();
}
res.write(template.render(data));
} catch(e) {
res.show500(e);
}
});
} catch(e) {
res.show500(e);
}
});
})(req, res);
} catch(e) {
res.show500(e);
}
Answer the question
In order to leave comments, you need to log in
I have an indirect relationship with node.js, but it always seemed to me that:
asyncFunction(args, function(error, result){})
auth.getUser(req, function(error,user) {
if (error != null){
handle(res,error);
return;
}
db.getData(function(error,data) {
if (error != null){
handle(res,error);
return;
}
res.write(template.render(data));
});
Take a look at thechangelog.com/post/516202796/step-control-flow-the-node-js-way
Just uniform error and exception handling.
We use domain http://habrahabr.ru/post/147233/
In general, the specifics of processing on a node is callback(error, data) where an error flies to the callback
Firebag - a mega-popular plugin for Mozilla Firefox, perfectly solves just this problem:
- in the console you see all incoming and outgoing requests
- you see the content of these requests
- you see how HTML and CSS change
- you see errors, incl. server error messages
- ...
Firebag is installed from the Mozilla Firefox menu->Edit->Preferences->Add-ons->Configure add-ons->Search for add-ons
generate an event everywhere - type error_500, and stop working. and in the event handler you already form a response to the user and display it. then in any code it is enough to generate an event and the user will have the desired page
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question