博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
nodejs 同步异步异常处理封装
阅读量:7090 次
发布时间:2019-06-28

本文共 2096 字,大约阅读时间需要 6 分钟。

hot3.png

一、同步异常处理

//app.js/** * 同步异常处理 */app.use(function errorHandler(err, req, res, next) {	var accept = accepts(req);	var type = accept.type('html', 'json', 'text');	var jsonResult = new JsonResult();	jsonResult.status = -1;	jsonResult.message = "系统繁忙";	logger.error('synchronous error on request %s %s: %s', req.method, req.url, err.message);	if(err.domain) {		logger.error("attention!!!, this is an unhandled error,please solve this problem as soon as possible!!!");	}	if(type === "json") {		var contentType = res.get("Content-Type");		//Content-Type为空,认为系统还没有处理过异常,这里进行处理		if(!contentType) {			var jsonResult = new JsonResult();			jsonResult.status = -1;			jsonResult.message = "系统繁忙";			res.json(jsonResult);		}	} else {		res.send(500, "系统繁忙");	}});app.use(errorHandler({ dumpExceptions: true, showStack: true }));

 

二、异步异常处理

//app.jsapp.use(require('express-domain-middleware'));var domain = require('domain');app.use(function (req, res, next) {	//https://nodejs.org/api/domain.html#domain_domain	//引入一个domain的中间件,将每一个请求都包裹在一个独立的domain中	//domain来处理异步异常	var d = domain.create();	//监听domain的错误事件	d.on('error', function (err) {		logger.error('asynchronous error on request %s %s: %s', req.method, req.url, err.message);		var contentType = res.get("Content-Type");		//Content-Type为空,认为系统还没有处理过异常,这里进行处理		if(!contentType) {			var jsonResult = new JsonResult();			jsonResult.status = -1;			jsonResult.message = "系统繁忙";			res.json(jsonResult);		}		//d.dispose();//释放一个domain对象 'domain.dispose() is deprecated	});	d.add(req);	d.add(res);	d.run(next);});

 

三、最终的异常处理

/** *落网的异常最后到了这里 */process.on('uncaughtException', function (err) {	console.error('serious error happend: ' + err);});

 

四、try catch

nodejs中大部分异常都是异步的,然try catch并不能捕获异步的异常。。。

 

五、关键点

使用过promise框架的人都知道promise框架本身也可以进行异常处理监听,如果方法已经对异常进行了处理的话就没必要再公共异常处理进行异常处理了,这里通过contentType来判断各自的方法是否已经对异常进行了处理,判断的依据就是是否设置了contentType。

 

 

六、memcached 和redis操作的异常处理

setTimeout(function () {                    throw new Error("dsf");                }, 100);

 

如果是memcached 和redis的异常处理,必须使用setTimeOut才能捕获到异常,这是domain的一个大坑。

 

 

 

 

 

转载于:https://my.oschina.net/fengshuzi/blog/731118

你可能感兴趣的文章
VS2017 远程调试小记
查看>>
php文件上传接口及文件上传错误服务器配置
查看>>
[实战]MVC5+EF6+MySql企业网盘实战(5)——页面模板
查看>>
JLOI2015 城池攻占
查看>>
Collection of Tools - Fix problems that programs cannot be installed or uninstalled
查看>>
快速搭建fabric-v1.1.0的chaincode开发环境
查看>>
Python学习的相关文件链接
查看>>
JSON 入门
查看>>
constructor中能不能有返回值?
查看>>
03动物类
查看>>
池化层pooling
查看>>
GPS坐标转百度地图并且加载地图示例.支持微信端访问
查看>>
npm -D -S 区别明细
查看>>
error:#70:incomplete type is not allowed FILE __stdout;
查看>>
react native windows开发环境搭建(一)
查看>>
nodejs 路径
查看>>
自动化运维工具之ansible
查看>>
TortoiseGit自动记住用户名密码的方法
查看>>
大白话5分钟带你走进人工智能-第十七节逻辑回归之交叉熵损失函数概念(2)
查看>>
如何给变量取个简短且无歧义的名字
查看>>