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 的作用,可以将异常向上层抛出,让上层代码进行捕获,实现异常消息的传递。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值