首页 > 解决方案 > 使用加密和节点解密时捕获错误

问题描述

我正在尝试解密加密文本。如果我提供正确的加密文本,它工作正常。但是如果我输入了错误的加密文本,节点应用程序就会崩溃。没有 try catch 块有帮助,也不会引发错误。

我可以做些什么来捕获错误并返回一个优雅的 500 错误。

app.post("/decrypt", (req, res) => {
  const key = crypto.scryptSync(password, "salt", 24);
  const iv = Buffer.alloc(16, 0);
  const decipher = crypto.createDecipheriv(algorithm, key, iv);
  let decrypted = "";
  decipher.on("readable", () => {
    while (null !== (chunk = decipher.read())) {
      decrypted += chunk.toString("utf8");
    }
  });
  decipher.on("end", () => res.json({ decrypted }));
  decipher.write(req.body.payload, "hex");
  decipher.end();
});

标签: node.jsencryptionnode-crypto

解决方案


鉴于您创建的解密对象是一个流,您可以侦听错误事件。


let hadErr;
decipher.on("end", () => {
  // not entirely sure this check is necessary
  // but I'll assume you get the end event either way
  if(!hadErr)
    res.json({ decrypted });
});
decipher.on('error', (err) => {
  hadErr = true;
  console.error(err);
  res.status(500);
  res.end('An error has occurred');
})
decipher.write(req.body.payload, "hex");

错误事件在整个节点库中很常见。如果发出错误事件并且它没有侦听器,它会变成一个未捕获的错误,默认情况下会使进程崩溃。


推荐阅读