nodejs 异常的处理

var http = require('http');
var url = require('url');
var router = require('./router');

http.createServer(function(request, response){
	
	if(request.url!=='/favicon.ico'){ // 防止第二次重复访问
		//response.writeHead(200,{'Contet-Type':'text/html;charset=utf-8'});
		var pathname = url.parse(request.url).pathname;
		pathname = pathname.replace(/\//,'');// 替换掉前面的 /
		console.log(pathname);
		try{
			router[pathname](request,response);
		}catch(err){
			console.log('错误为:'+err);
			response.writeHead(200,{'Contet-Type':'text/html;charset=utf-8'});
			response.write(err.toString());
			response.end('');
		}
		console.log('server 执行完毕。');
	}
}).listen(8000);
console.log('Server is running in port 8000');
var readhtml = require('./readhtml');

function getRecall(req,res){
	res.writeHead(200,{'Contet-Type':'text/html;charset=utf-8'});
	function recall(data){
		res.write(data)
		res.end('');
	}
	return recall;
}
module.exports={
	login:function(req,res){
		recall = getRecall(req,res);
		readhtml.login('./html/login.html',recall);// 不存在文件login111.html
		console.log("login====");
	},
	showImg:function(req,res){
		res.writeHead(200,{'Contet-Type':'image/jpeg'});
		readhtml.showimg('./img/1.jpg',res);
		console.log("login====");
	}
}
var fs = require('fs');

module.exports = {
	login:function(path,recall){
		fs.readFile(path,function(err,data){
			if(err){
				console.log(err)
				recall('文件不存在。') // 返回异常信息
			}else{
				recall(data);
			}	
		});
	},
	showimg:function(path,res){
		fs.readFile(path,'binary',function(err,filedata){
			if(err){
				console.log(err);
				return;
			}else{
			
				res.write(filedata,'binary');
				res.end('');
			}
		});
	}

}

同步代码用try catch;异步代码直接在异步捕获的异常中返回如下图,当login.html不存在的时候

抛出异常

var http = require('http');
var url = require('url');
var router = require('./router');

var exp = require('./exp');

http.createServer(function(request, response){
	
	if(request.url!=='/favicon.ico'){ // 防止第二次重复访问
		//response.writeHead(200,{'Contet-Type':'text/html;charset=utf-8'});
		var pathname = url.parse(request.url).pathname;
		pathname = pathname.replace(/\//,'');// 替换掉前面的 /
		console.log(pathname);
		try{
			//router[pathname](request,response);
			var str = exp.exp(0);
			response.write(str);
			response.end('');

		}catch(err){
			console.log('错误为:'+err);
			response.writeHead(200,{'Contet-Type':'text/html;charset=utf-8'});
			response.write(err.toString());
			response.end('');
		}
		console.log('server 执行完毕。');
	}
}).listen(8000);
console.log('Server is running in port 8000');
module.exports ={
	exp:function(data){
		if(data==0){
			throw '我是异常信息';
		}
		return '成功';
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值