栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用node.js的Javascript异步异常处理

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用node.js的Javascript异步异常处理

警告
:我不建议使用域的原始答案,以后将不建议使用域,编写原始答案很有趣,但我不再相信它太相关了。相反,我建议使用事件处理程序和具有更好错误处理的Promise,以下是使用Promise的示例。这里使用的承诺是Bluebird:

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

超时(请注意,我们必须返回Promise.delay):

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

使用一般的NodeJS函数:

var fs = Promise.promisifyAll("fs"); // creates readFileAsync that returns promisefs.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});

这种方法既快速又安全,我建议在下面的答案上方使用它,因为它使用的域可能不会保留下来。


我最终使用了域,创建了以下文件

mistake.js
,其中包含以下代码:

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;    };};

这是一些示例用法:

var atry = require("./mistake.js");atry(function() {    setTimeout(function(){        throw "something";    },1000);}).catch(function(err){    console.log("caught "+err);});

它也像正常捕获同步代码一样工作

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

我希望对解决方案有一些反馈

另外,显然在v
0.8中,当您在域中捕获异常时,它仍然冒泡到

process.on("uncaughtException")
。我处理这在我
process.on("uncaughtException")

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

但是,文档建议采取

process.on("uncaughtException")
任何方式



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/452425.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号