还是上一篇博文的情景,如果用户输入的不是localhost:3000/login怎么办,此时就需要捕获异常

n9_exception.js

var http =  require('http');                                        
var url = require('url');
var router = require('./models/router');
var exception = require('./models/Exception');
http.createServer(function (request,response){
if(request.url!=="/favicon.ico"){ //清除第2此访问
pathname=url.parse(request.url).pathname;
pathname = pathname.replace(/\//,'');//替换掉前面的/
try{
router[pathname](request,response);
/* data = exception.expfun(0);
response.write(data);
response.end(''); */
}catch(err){
console.log('aaaaa='+err);
response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
//向页面输出错误信息
response.write(err.toString());
response.end('');
}
console.log("server执行完毕");
}
}).listen(3000);
console.log('Server running at http://127.0.0.1:3000/');

./models/Exceptiom.js

module.exports={      
expfun:function(flag){
if(flag==0){
throw '我是例外';
}
return "success";
}
}

当用户访问的不是login页面时运行结果:


node.js学习之异常初步_ico