node.js - 使用加密和节点解密时捕获错误
问题描述
我正在尝试解密加密文本。如果我提供正确的加密文本,它工作正常。但是如果我输入了错误的加密文本,节点应用程序就会崩溃。没有 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();
});
解决方案
鉴于您创建的解密对象是一个流,您可以侦听错误事件。
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");
错误事件在整个节点库中很常见。如果发出错误事件并且它没有侦听器,它会变成一个未捕获的错误,默认情况下会使进程崩溃。
推荐阅读
- css - @import 路径上的意外插值
- c++ - 为什么我的向量初始化使我的数组中的所有对象都相同?
- java - 无法在单个 dex 文件中容纳请求的类(# 方法:86965 > 65536)
- react-select - 如何使 react-select 可搜索始终显示清晰的指示符
- django - 在 Django 中显式实现 LEFT JOIN
- iis - 如何在 web.config 中指定文件路径以检查文件是否存在?
- python - 如何使用 python 从 pdf 文件中使用 camelot 提取表名和表?
- arduino - 智能灌溉系统中的代码错误,使用 dht11 传感器
- smartsheet-c#-sdk-v2 - Smartsheet C# 包装器编码字符
- reactjs - 动态设置 axios 基本 url