ノード.js異常処理

18982 ワード

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を訪問します.Node.js 异常处理_第1张图片
私たちは存在しないpathnameを訪問しました.Node.js 异常处理_第2张图片
Node.js 异常处理_第3张图片
もし私たちのエラーがrouter.jsのlognメソッドに異常が発生したら、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);
    }


}
再アクセス:这里写图片描述プログラムの実行は完了しましたが、ブラウザは応答を待っています.ロゴの中のreadfile方法に異常が発生し、プログラムはifに進んでいますので、プログラムはレスポンス・エンドを行いませんでした.
Node.js 异常处理_第4张图片バックグラウンドにエラーが発生しました.
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();
            }
        });
    }
}
这里写图片描述
これにより、ブラウザの応答待ちの問題が解決され、Recal()を呼び出す方法で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');
上記の異常データNode.js 异常处理_第5张图片バックグラウンド出力Node.js 异常处理_第6张图片throwからの異常がtry、catchによって捉えられました.これは異常なスロットルの役割であり、異常を上層部に投げ出して上層部のコードを捕獲し、異常メッセージを伝えることができる.