这篇文章给大家详细介绍了如何在node.js下自定义错误类型,对大家学习或者使用node.js具有一定的参考借鉴价值,有需要的朋友们可以参考借鉴,下面来一起看看吧。
前言
一般来说,很少人会考虑如何处理应用产生的错误的策略,调试的过程中,简单地利用console.log(‘error')定位错误,基本够用了,通过留下这些调试信息,能够为我们以后的调试过程中升了不少时间,提高了维护性。所以错误提示非常重要。同时,也会带来一些比较糟糕用法。最近的项目里就用到了自定义错误类型,觉得有必要深入了解一下,所以就写了这篇文章,方便自己和有需要的大家在需要的时候查阅。
subclassing error
首先我们可以定义一个 error 的子类。通过 object.create 和 util.inherits 很容易实现:
var assert = require('assert');var util = require('util');function notfound(msg){ error.call(this); this.message = msg;}util.inherits(notfound, error);var error = new notfound('not found');assert(error.message);assert(error instanceof notfound);assert(error instanceof error);assert.equal(error instanceof rangeerror, false);
可以通过 instanceof 来检查错误类型,根据类型进行不同的处理。
上面的代码设置了自带的message, 并且 error 是 notfound 和 error 的一个实例, 但是不是 rangeerror。
如果用了 express 框架, 就能设置其他的 properties 让 error 变得更有用。
比方说当处理一个http的错误时, 就可以写成这样:
function notfound(msg) { error.call(this); this.message = msg; this.statuscode = 404;}
现在就已经可以通过错误处理的中间件来处理错误信息:
app.use(function(err, req, res, next) { console.error(err.stack); if (!err.statuscode || err.statuscode === 500) { emails.error({ err: err, req: req }); } res.send(err.statuscode || 500, err.message);});
这会发送http的状态码给浏览器, 当 err 的 statuscode 未设置或者等于 500 的时候, 就通过邮件来发送这个错误。这样就能排除那些 404, 401, 403等等的错误。
读取 console.error(err.stack) 事实上并不会像预期那样工作,像 node, chrome 基于 v8 的可以使用 error.capturestacktrace(this, arguments.callee) 的错误构造函数来进行堆栈跟踪。
var notfound = function(msg) { error.call(this); error.capturestacktrace(this, arguments.callee); this.message = msg || 'not found'; this.statuscode = 404; this.name = "notfound"}util.inherits(notfound, error);export.notfounderror = notfound;
当然我们还可以将上面这个创建的抽象错误类型扩展到其他自定义错误中:
var notfounterror = require('./error').notfounterror; var usernotfound = function(msg){ this.constructor.super_(msg);}util.inherits(usernotfound, notfounderror);
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注!
相关推荐:
nodejs中模块定义的介绍
nodejs实现bigpipe异步加载页面的方法
关于node.js基于fs模块对系统文件及目录进行读写操作的方法
以上就是node.js下自定义错误类型的解析的详细内容。