最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Asynchronous Exception Handling with node.js - Stack Overflow

programmeradmin5浏览0评论

I'm currently working on a node.js app and I'm having the usual asynchronous code issue.

I'm implementing a service server on top of Node's HTTP module.

This server supports (express like) routes. For example I have code that looks like this:

server.any("/someRoute",function(req,resp){
    resp.end("this text is sent to clients via http")
});

The server needs to be able to withstand failure, I do not want to crash the whole server when there is a problem in a function passed to any. The problem occurs when I'm writing code that looks like:

server.any("/someRoute",function(req,resp){
    setTimeout(function(){
        throw new Error("This won't get caught");
    },100);
});

I don't see how I possible can catch the error here. I don't want to crash the server over one server-side glitch, instead I want to serve 500.

The only solutions I've been able to come up with are really not expressive. I've only come up with using process.on("uncaughtException",callback) and similar code using node 0.8 Domains (which is a partial remedy but Domains are currently buggy and this is still not very expressive since I end up having to create a domain for every handle).

What I would like to accomplish is binding throw actions from a function to a scope, the ideal solution is something like binding all thrown errors from a function to a specific handler function.

Is this possible? What is the best practice to handle errors in this case?

I'd like to emphasise that it should be able to continue serving requests after a bad requests, and restarting the server on every request or creating domains for every handler and catching their uncaught exceptions seems like a bad idea to me. Additionally - I've heard promises might be able to assist me (something about throw in promises), can promises aid me in this situation?

I'm currently working on a node.js app and I'm having the usual asynchronous code issue.

I'm implementing a service server on top of Node's HTTP module.

This server supports (express like) routes. For example I have code that looks like this:

server.any("/someRoute",function(req,resp){
    resp.end("this text is sent to clients via http")
});

The server needs to be able to withstand failure, I do not want to crash the whole server when there is a problem in a function passed to any. The problem occurs when I'm writing code that looks like:

server.any("/someRoute",function(req,resp){
    setTimeout(function(){
        throw new Error("This won't get caught");
    },100);
});

I don't see how I possible can catch the error here. I don't want to crash the server over one server-side glitch, instead I want to serve 500.

The only solutions I've been able to come up with are really not expressive. I've only come up with using process.on("uncaughtException",callback) and similar code using node 0.8 Domains (which is a partial remedy but Domains are currently buggy and this is still not very expressive since I end up having to create a domain for every handle).

What I would like to accomplish is binding throw actions from a function to a scope, the ideal solution is something like binding all thrown errors from a function to a specific handler function.

Is this possible? What is the best practice to handle errors in this case?

I'd like to emphasise that it should be able to continue serving requests after a bad requests, and restarting the server on every request or creating domains for every handler and catching their uncaught exceptions seems like a bad idea to me. Additionally - I've heard promises might be able to assist me (something about throw in promises), can promises aid me in this situation?

Share Improve this question edited Dec 22, 2014 at 11:06 Benjamin Gruenbaum asked Jan 13, 2013 at 8:25 Benjamin GruenbaumBenjamin Gruenbaum 276k89 gold badges518 silver badges514 bronze badges 5
  • AFAIK, catching thrown exceptions from async code is impossible outside of something like domains (which sounds exaclty like "binding all thrown errors from a function to a specific handler function"); the alternative is to use the standard Node.js callback style where the first parameter is an error instead of throwing (and is in fact why this pattern is so prevalent). – Michelle Tilley Commented Jan 13, 2013 at 8:31
  • I have to be able to work with code I did not write on my own. The dream solution would be something like functionName.exceptionHandler = someFunction(exception) or something of the sort. – Benjamin Gruenbaum Commented Jan 13, 2013 at 8:33
  • Totally understand--but I'm not sure you'll get that very easily. You have to intercept the calls (which is what Domains attempts to do for built-in event emitters). (Perhaps some theoretical extension of JavaScript--think CoffeeScript--could do the necessary code generation for you.) The fact of the matter is, throwing from asynchronous code is bad form, and for instance where it can't be helped (perhaps a JSON.parse fails, etc.), the uncaughtException event is your ticket to saving your app (although it would surely be better for the library to catch inside its own code). – Michelle Tilley Commented Jan 13, 2013 at 8:44
  • @BrandonTilley I would appreciate your feedback on my own answer – Benjamin Gruenbaum Commented Jan 13, 2013 at 13:43
  • @BenjaminGruenbaum Can you answer this stackoverflow.com/questions/43069522/… – user7350714 Commented Mar 28, 2017 at 15:12
Add a comment  | 

1 Answer 1

Reset to default 20

Warning: I would not recommend the original answer using domains, domains are being deprecated in the future, I had a lot of fun writing the original answer but I no longer believe it is too relevant. Instead - I suggest using event emitters and promises that have better error handling - here is the below example with promises instead. The promises used here are Bluebird:

Promise.try(function(){ 
    throw new Error("Something");
}).catch(function(err){
    console.log(err.message); // logs "Something"
});

With a timeout (note that we have to return the Promise.delay):

Promise.try(function() {
    return Promise.delay(1000).then(function(){
        throw new Error("something");
    });
}).catch(function(err){
    console.log("caught "+err.message);
});

With a general NodeJS funciton:

var fs = Promise.promisifyAll("fs"); // creates readFileAsync that returns promise
fs.readFileAsync("myfile.txt").then(function(content){
    console.log(content.toString()); // logs the file's contents
    // can throw here and it'll catch it
}).catch(function(err){
    console.log(err); // log any error from the `then` or the readFile operation
});

This approach is both fast and catch safe, I recommend it above the below answer which uses domains that are likely not here to stay.


I ended up using domains, I have created the following file I called mistake.js which contains the following code:

var domain=require("domain");
module.exports = function(func){
    var dom = domain.create();
    return { "catch" :function(errHandle){
        var args = arguments;
        dom.on("error",function(err){
            return errHandle(err);
        }).run(function(){
            func.call(null, args);
        });
        return this;
    };
};

Here is some example usage:

var atry = require("./mistake.js");

atry(function() {
    setTimeout(function(){
        throw "something";
    },1000);
}).catch(function(err){
    console.log("caught "+err);
});

It also works like normal catch for synchronous code

atry(function() {
    throw "something";
}).catch(function(err){
    console.log("caught "+err);
});

I would appreciate some feedback on the solution

On a side note, in v 0.8 apparently when you catch the exception in the domain it still bubbles to process.on("uncaughtException"). I dealt with this in my process.on("uncaughtException") with

 if (typeof e !== "object" || !e["domain_thrown"]) {

However, the documentation suggests against process.on("uncaughtException") any way

发布评论

评论列表(0)

  1. 暂无评论