node基础10:处理异常

1.处理异常

当发生异常时,如果不作处理,那么服务器会奔溃。由于node的异步调用的特性,所以不但要考虑主程序的异常,还有处理异步调用的异常。

代码如下:

/**
 * server.js 
 */
var http = require('http');
var url = require('url');
var router = require('./router');
var exception = require('./exception')
http.createServer(function(req, res){
    if ( req.url !== '/favicon.ico'){
        pathname = url.parse(req.url).pathname.replace(/\//,'');
        console.log(pathname);
        try {
            // console.log('success');
            // data = exception.exp(1);
            // res.write(data);
            // res.end();
            router[pathname](req, res);
        } catch(e) {
            console.log('error:'+e);
            res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
            res.write(e.toString());
            res.end();
        };
    }
}).listen(3000);
console.log("server running at http:127.0.0.1:3000");
/**
 * router.js
 */
var fs = require('fs');
module.exports = {
    login: function(req, res){
        fs.readFile('./login.html', function(err, data){
            if( err){
                console.log(err);
                res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'})
                res.write(err.toString());
                res.end();
                return;
            } else {
                res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'})
                res.write(data);
                res.end();
            }
        })
    },
    register:function(req, res){
        fs.readFile('.register.html', function(err, data){
            if(err) {
                console.log(err);
                res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'})
                res.write(err.toString());
                res.end();
                return;
            } else{
                res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
                res.write(data);
                res.end();
            }
        })
    },
    showImage:function(req, res){
        fs.readFile('./test.png',function(err, data){
            if (err) {
                console.log(err);
                return;
            } else{
                console.log("开始读取图片");
                res.writeHead(200, {'Content-Type':'image/jpeg'});
                res.write(data);
                res.end();//写在互调函数外面会报错的哟
            }
        })
    }

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

在上述的 try {} catch(err) {} 中,虽然 try中无错误,但是在try 中执行了一个异步调用,这个调用不会被主程序捕获到,所以在异步调用中再次处理异常。

posted on 2017-01-05 21:33  码先生  阅读(334)  评论(0)    收藏  举报