nodejs 异常的处理

版权声明:版权有就有吧。 https://blog.csdn.net/m0_38044453/article/details/83749802
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 '成功';
	}
}

猜你喜欢

转载自blog.csdn.net/m0_38044453/article/details/83749802
今日推荐