Node.js Nodejs如何防止模块崩溃(加密)
我使用一个模块来加密/解密数据Node.js Nodejs如何防止模块崩溃(加密),node.js,error-handling,module,Node.js,Error Handling,Module,我使用一个模块来加密/解密数据 var crypto = require('crypto'); function encrypt(text){ var cipher = crypto.createCipher('aes-256-cbc','secret key'); var encrypted = cipher.update(text.toString(),'utf8','hex') + cipher.final('hex'); return encrypted; }
var crypto = require('crypto');
function encrypt(text){
var cipher = crypto.createCipher('aes-256-cbc','secret key');
var encrypted = cipher.update(text.toString(),'utf8','hex') + cipher.final('hex');
return encrypted;
}
function decrypt(text){
var decipher = crypto.createDecipher('aes-256-cbc','secret key');
var decrypted = decipher.update(text.toString(),'hex','utf8') + decipher.final('utf8');
return decrypted ;
}
module.exports.encrypt = encrypt;
module.exports.decrypt = decrypt;
并将其加载到我的路线中:
var crypt = require('./middleware/encrypt');
var id = 10;
var id_crypted = crypt.encrypt(id);
console.log(id_crypted);
var id_decrypted = crypt.decrypt(id_crypted);
console.log(id_decrypted);
所以这很好(除了我必须在crypt模块中使用text.toString(),否则它会崩溃..)
问题出在解密上。
我无法控制将被解密的数据(我从cookie中获取它们)
例如,如果我想解密值“10”,那么我的所有应用程序都会崩溃,因为解密函数会抛出一个关于错误的最终块长度的错误
那么,当出现错误时,如何防止我的模块使我的所有应用程序崩溃呢?这应该可以工作
process.on('uncaughtException', function(error) {
console.log(error.stack);
});
摘自将有问题的函数调用包装在try-catch块中。谢谢。我需要把它放在我的app.js上的什么地方?启动脚本中的任何地方都应该这样做。建议将它放在底部,这样你就不必一直滚动它了。请注意,uncaughtException是一种非常粗糙的异常处理机制,将来可能会被删除。我认为这不是一个好的解决办法