Node.js异常(例外)处理

一、异常处理

1、比如输入浏览器的路由的时候,当路由输入一个不存在的路径的时候,这个时候就会直接报错,报错之后server就会崩溃,然后就要手动启动服务,对于一个服务器而言是不能容忍的。这个时候就要用到异常处理。

2、分类

    同步异常处理

    异步异常处理

二、同步的异常处理

(一)、输入正确的路由

1、n9

var http  = require('http');                                        
var url = require('url');        
var luyou = require('./luyou');    
http.createServer(function  (request,response){                                        
              if(request.url!=="/favicon.ico"){ //清除第2此访问                
					pathname=url.parse(request.url).pathname;        
					pathname = pathname.replace(/\//,'');//替换掉前面的/        
					try{        
                       luyou[pathname](request,response);    
				
					}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(8000);                                        
console.log('Server running  at http://127.0.0.1:8000/');

2、运行

(二)、输入不正确的路由

三、异步的异常处理

只需要修改两处:

1、假设 luyou

var optfile = require('./models/optfile');
//封装
function getRecall(req ,res ){
	res.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});
	function recall(data){
			res.write(data);
			res.end('');//不写则没有http协议尾
	}
	return recall;
}

module.exports={
	//进入
    login:function(req,res){
    recall =getRecall(req ,res);
    optfile.readfile('..../views/login.html',recall);  //路径写错
    },
	//注册
    setin:function(req,res){
		recall =getRecall(req ,res);
		optfile.readfile('./views/setin.html',recall);
    },
	//写入
	writefile:function(req ,res){
		recall =greRecall(req ,res);
		optfile.writefile('./views/one.text','天气好好!!!',recall);
	},
	//读图片
	showimg:function(req ,res){
		res.writeHead(200,  {'Content-Type':'image/jpeg'}); 
		optfile.readImg('./imgs/pig.png',res); 
	}
	
}'..../views/login.html',recall);  //路径写错
    },
	//注册
    setin:function(req,res){
		recall =getRecall(req ,res);
		optfile.readfile('./views/setin.html',recall);
    },
	//写入
	writefile:function(req ,res){
		recall =greRecall(req ,res);
		optfile.writefile('./views/one.text','天气好好!!!',recall);
	},
	//读图片
	showimg:function(req ,res){
		res.writeHead(200,  {'Content-Type':'image/jpeg'}); 
		optfile.readImg('./imgs/pig.png',res); 
	}
	
}

2、optfile

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){
			//如果错误err
            if(err){
              console.log("nnnn:"+err);
	      recall("文件不存在");  //添加
            }else{
              console.log(data.toString());
	      recall(data);
            }
        });
        console.log("异步方法执行完毕");
    },
	
	//读取二进制图片(传入路径)
	readImg:function(path,res){
        fs.readFile(path,'binary',function(err,filedata)  { //异步执行  'binary' 二进制流的文件
            if  (err)  {
                console.log(err);
                return;
            }else{
				res.write(filedata,'binary');
				res.end();
            }
        });
    },
	
	//写文件
    writefile:function(path,data,recall){    //异步方式
        fs.writeFile(path,  data,  function  (err)  {
            if  (err)  {
                throw  err;
            }
            console.log('It\'s  saved!');  //文件被保存
			recall('写文件成功!');
          });
    },
    writeFileSync:function(path,data){  //同步方式
        fs.writeFileSync(path,  data);
        console.log("同步写文件完成");
    },	
}
  console.log("nnnn:"+err);
	      recall("文件不存在");  //添加
            }else{
              console.log(data.toString());
	      recall(data);
            }
        });
        console.log("异步方法执行完毕");
    },
	
	//读取二进制图片(传入路径)
	readImg:function(path,res){
        fs.readFile(path,'binary',function(err,filedata)  { //异步执行  'binary' 二进制流的文件
            if  (err)  {
                console.log(err);
                return;
            }else{
				res.write(filedata,'binary');
				res.end();
            }
        });
    },
	
	//写文件
    writefile:function(path,data,recall){    //异步方式
        fs.writeFile(path,  data,  function  (err)  {
            if  (err)  {
                throw  err;
            }
            console.log('It\'s  saved!');  //文件被保存
			recall('写文件成功!');
          });
    },
    writeFileSync:function(path,data){  //同步方式
        fs.writeFileSync(path,  data);
        console.log("同步写文件完成");
    },	
}

3、运行

============================================================================

四、异常的抛出 -- throw (抛出字符串、对象、数组等)

用try-catch 拿到抛出的异常,作为廉价的消息传递机制 。

1、exception

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

2、n9修改

var http  = require('http');                                        
var url = require('url');        
var luyou = require('./luyou');    
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{        
                       //luyou[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(8000);                                        
console.log('Server running  at http://127.0.0.1:8000/');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{        
                       //luyou[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(8000);                                        
console.log('Server running  at http://127.0.0.1:8000/');

3、运行

4、或者n9修改为

var http  = require('http');                                        
var url = require('url');        
var luyou = require('./luyou');    
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{        
                       //luyou[pathname](request,response);    
			data  =  exception.expfun(10);
			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(8000);                                        
console.log('Server running  at http://127.0.0.1:8000/');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{        
                       //luyou[pathname](request,response);    
			data  =  exception.expfun(10);
			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(8000);                                        
console.log('Server running  at http://127.0.0.1:8000/');

5、运行

两次结果是不一样的!!

Node.js 中使用 Thrift 进行开发时,异常处理是非常重要的一部分。下面是一些基于 Thrift 的 Node.js 异常处理的技巧: 1. 在客户端和服务器端都需要处理异常。在客户端,您可以使用 try-catch 块来捕获 Thrift 调用中的异常。在服务器端,您可以为每个服务实现设置错误处理程序来捕获异常。您可以使用以下代码在服务器端设置异常处理程序: ``` var myServiceHandler = { myMethod: function (params, result) { try { // Service implementation } catch (e) { // Handle errors result(new thrift.TApplicationException(thrift.TApplicationException.INTERNAL_ERROR, "Internal error")); } } }; var processor = new thrift.Processor(myServiceHandler); ``` 2. 在客户端和服务器端都应该使用 TApplicationException 类处理异常。TApplicationException 类可用于传递错误消息和错误代码。在客户端,您可以使用此类来获取有关远程服务调用的错误信息。在服务器端,您可以使用此类来向客户端传递错误信息。 3. 在 Thrift 调用中,您可以使用 Promise 或回调函数来处理异步调用。在使用 Promise 时,您可以使用 then() 和 catch() 方法来处理成功和失败的情况。在使用回调函数时,您可以在回调函数中处理异常。以下是使用 Promise 处理异常的示例代码: ``` var client = new myServiceClient(connection); client.myMethod(params) .then(function (result) { // Handle success }) .catch(function (error) { // Handle error }); ``` 4. 最后,建议使用日志记录库来记录异常信息。这将有助于您诊断问题并了解哪些异常最频繁发生。 希望以上技巧能够帮助您在 Node.js 中正确处理 Thrift 异常
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值