Node.js 异常处理
var http = require('http');
var url = require('url');
var router = require('./router');
http.createServer(function(request,response){if(request.url != '/favicon.ico'){var pathname = url.parse(request.url).pathname;pathname = pathname.replace(/\//,''); //替换掉前面的'/'console.log("Request for " + pathname + " received.");router[pathname](request,response);}
}).listen(8000);console.log('Server running at http://127.0.0.1:8000');
我们之前的项目中,如果我们去调用router[pathname](request,response);
并且访问一个不存在的pathname,那么我们的程序就会报错。为了避免,我们可以使用try和catch来捕获异常。
var http = require('http');
var url = require('url');
var router = require('./router');
http.createServer(function(request,response){if(request.url != '/favicon.ico'){var pathname = url.parse(request.url).pathname;pathname = pathname.replace(/\//,''); //替换掉前面的'/'console.log("Request for " + pathname + " received.");try{router[pathname](request,response);}catch(err){console.log("error:" + err);response.writeHead(200,{'Content-Type' : 'text/html; charset=UTF-8'});response.write(err.toString());response.end('');}}
}).listen(8000);console.log('Server running at http://127.0.0.1:8000');
router.js
var optfile = require('./fs_read');function getRecall(req,res){function recall(data){res.writeHead(200,{'Content-Type' : 'text/html; charset=UTF-8'});res.write(data);res.end(''); }return recall;
}module.exports = {login : function(req,res){recall = getRecall(req,res);optfile.readfile('login.html',recall);},register : function(req,res){recall = getRecall(req,res);optfile.readfile('register.html',recall);},showImg : function(req,res){res.writeHead(200,{'Content-Type' : 'image/jpeg'});optfile.readImg('./1.png',res);}}
我们访问一个存在的pathname:
我们访问一个不存在的pathname:
如果我们的错误异常出现在router.js的login方法中,在readfile中读取一个不存在的文件,我们是否还能捕获异常呢?
我们修改router.js如下:
var optfile = require('./fs_read');function getRecall(req,res){function recall(data){res.writeHead(200,{'Content-Type' : 'text/html; charset=UTF-8'});res.write(data);res.end(''); }return recall;
}module.exports = {login : function(req,res){recall = getRecall(req,res);optfile.readfile('login1.html',recall);//修改为不存在的文件},register : function(req,res){recall = getRecall(req,res);optfile.readfile('register.html',recall);},showImg : function(req,res){res.writeHead(200,{'Content-Type' : 'image/jpeg'});optfile.readImg('./1.png',res);}}
再重新访问:
程序执行完毕,但浏览器一直在等待响应,因为在login中的readfile方法中就出现异常了,程序走进了if(err),所以程序没有进行response.end()结束。
后台已经打印出错误。
var fs = require("fs");module.exports = {readfileSync : function(path){//同步读取var data = fs.readFileSync(path,'utf-8');console.log(data);console.log("同步方法执行完毕");},readfile : function(path,recall){//异步执行fs.readFile(path,function(err,data){if(err){console.log(err);}else{recall(data); //回调recall函数,它是闭包函数,它会存储原来的response对象console.log(data.toString());}});console.log("异步方法执行完毕");},readImg : function(path,res){fs.readFile(path,'binary',function(err,file){if(err){console.log(err);return ;}else{res.write(file,'binary');res.end();}});}
}
因为在readfile 中的调用的fs.readFile()中的事件回调的第一个参数就是err,当读取文件出现错误的时候,就会放入err参数中,最后被打印出来了。所以异常就在这个地方报来了。
我们进行如下修改:
var fs = require("fs");module.exports = {readfileSync : function(path){//同步读取var data = fs.readFileSync(path,'utf-8');console.log(data);console.log("同步方法执行完毕");},readfile : function(path,recall){//异步执行fs.readFile(path,function(err,data){if(err){console.log(err);recall("文件不存在");}else{recall(data); //回调recall函数,它是闭包函数,它会存储原来的response对象console.log(data.toString());}});console.log("异步方法执行完毕");},readImg : function(path,res){fs.readFile(path,'binary',function(err,file){if(err){console.log(err);return ;}else{res.write(file,'binary');res.end();}});}
}
这样就解决了一直浏览器等待响应的问题,在调用recall()方法中执行了end()方法。
总结:在同步的代码中,可以使用try、catch捕获异常,但是在异步的代码中,try、catch是捕获不到异步中的异常,通常是通过异步代码中的事件回调中的error参数进行捕获异常的。
下面我们来讲讲异常的抛出:
我们利用之前的代码写一个例子:
module_expection.js
module.exports = {expfun : function(flag){if(flag == 0){throw '我是例外.';}return "success";}
}
var http = require('http');
var url = require('url');
var router = require('./router');
var exception = require('./module_exception');
http.createServer(function(request,response){if(request.url != '/favicon.ico'){var pathname = url.parse(request.url).pathname;pathname = pathname.replace(/\//,''); //替换掉前面的'/'console.log("Request for " + pathname + " received.");try{data = exception.expfun(1);response.write(data);response.end('');}catch(err){console.log("error:" + err);response.writeHead(200,{'Content-Type' : 'text/html; charset=UTF-8'});response.write(err.toString());response.end('');}}
}).listen(8000);console.log('Server running at http://127.0.0.1:8000');
上面我们传入一个正常的数据
var http = require('http');
var url = require('url');
var router = require('./router');
var exception = require('./module_exception');
http.createServer(function(request,response){if(request.url != '/favicon.ico'){var pathname = url.parse(request.url).pathname;pathname = pathname.replace(/\//,''); //替换掉前面的'/'console.log("Request for " + pathname + " received.");try{data = exception.expfun(0);response.write(data);response.end('');}catch(err){console.log("error:" + err);response.writeHead(200,{'Content-Type' : 'text/html; charset=UTF-8'});response.write(err.toString());response.end('');}}
}).listen(8000);console.log('Server running at http://127.0.0.1:8000');
上面我们传入一个异常的数据
而且后台输出
因为throw出来的异常被try、catch捕获到了。
这就是异常抛出throw 的作用,可以将异常向上层抛出,让上层代码进行捕获,实现异常消息的传递。
Node.js 异常处理相关推荐
- node.js入门 - 7.异常处理与多进程开发
node.js入门 - 7.异常处理与多进程开发 参考文章: (1)node.js入门 - 7.异常处理与多进程开发 (2)https://www.cnblogs.com/softlover/arch ...
- 图灵访谈系列之九:CNode社区谈Node.js技术及生态
Node.js在各种技术会议上的分享越来越火热,为了让更多的人了解Node.js以及Node.js中文技术社区CNode,12月10日在易宝支付举行第三期Node.js北京分享会--NodeParty ...
- Node.js:get/post请求、全局对象、工具模块
一.GET/POST请求 在很多场景中,我们的服务器都需要跟用户的浏览器打交道,如表单提交.表单提交到服务器一般都使用 GET/POST 请求. 1.获取GET请求内容 由于GET请求直接被嵌入在路径 ...
- node.js Web应用框架Express入门指南
node.js Web应用框架Express入门指南 作者: 字体:[增加 减小] 类型:转载 时间:2014-05-28 我要评论 这篇文章主要介绍了node.js Web应用框架Express入门 ...
- Node.JS 学习路线图
2019独角兽企业重金招聘Python工程师标准>>> 从零开始nodejs系列文章, 将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发.Nodejs框 ...
- js和python哪个好_Python与Node.JS:哪一个比较适合您的项目?
在进行新项目时选择正确的编程语言可能是程序员经常做出的比较艰巨的决定之一. 这个挑战背后的原因是,每个新项目都会遇到一个独特的问题,并且在编程世界中,没有任何行业的大师. 不同的编程语言都有其长处和短 ...
- 基于阿里云的 Node.js 稳定性实践
前言 如果你看过 2018 Node.js 的用户报告,你会发现 Node.js 的使用有了进一步的增长,同时也出现了一些新的趋势. Node.js 的开发者更多的开始使用容器并积极的拥抱 Serve ...
- js提交出现post错误_阿里云的 Node.js 稳定性实践
整理人:前端自习课 前言 如果你看过 2018 Node.js 的用户报告,你会发现 Node.js 的使用有了进一步的增长,同时也出现了一些新的趋势. Node.js 的开发者更多的开始使用容器并积 ...
- Node.js Domain 模块
Node.js 工具模块 Node.js Domain(域) 简化异步代码的异常处理,可以捕捉处理try catch无法捕捉的异常.引入 Domain 模块 语法格式如下: var domain = ...
最新文章
- redistemplate.opsforhash设置过期时间_Redis详解(十一)------ 过期删除策略和内存淘汰策略...
- python—函数进阶-迭代器
- 这场论文复现的华山论剑,谁能拔得头筹
- maven设置socks代理
- 库克斯坦福大学毕业演讲批评硅谷现状:我们有责任改变方向
- 【机器学习】Andrew Ng——04多变量线性回归
- mysql6.0_MySQL6.0安装
- 如何为复杂页面实现过渡页面
- JsonHelper 操作帮助类
- 光学定位与追踪技术_视觉SLAM技术学习笔记(一)基础知识以及SLAM的应用
- 微博中微服务缓存_新浪微博温情:基于微服务的微博直播互动架构设计经验分享...
- 西门子PLC与安川变频器Modbus通信
- Oracle 小写金额转换为大写金额
- 如何修改鼠标指针的样式
- 计算机怎么升级64位操作系统,如何将计算机的32位更改为64位
- Python 数据采集-爬取学校官网新闻标题与链接(基础)
- CSS-Grid(网格)布局
- 【SAS应用统计分析】软件的基本操及SAS数据集的整理
- iphone相册储存空间已满_iPhone手机提示icloud储存空间已满怎么办?icloud储存空间已满怎么解决?...
- malloclab 实验详解(动态分配器如何设计)