假设我在routes.js 文件中有这个伪代码:
var pkg = require('random-package');
app.post('/aroute', function(req, res) {
pkg.impl_func(data, function (err, result) {
myFunction(entity).then(user=>{
//DO_STUFF_HERE
res.render('page.ejs');
}).catch(err => {
console.log(err);
res.render('error.ejs');
});
});
});
function myFunction(username) {
//.....
}
我使用的pkg是在npmjs网站上找到的。 myFunction()
始终是我的函数。
在我的代码中,您可以看到我已经在 myFunction()
失败时实现了 then/catch 语句。
因此,当发生这种情况时,会呈现 error.ejs
。
但是当 npm 包失败时会发生什么?
在终端中,我收到错误消息,但服务器端没有错误处理。
这意味着,当失败时,用户将不会收到 error.ejs
通知,这是显而易见的,因为我的代码中省略了此功能。
但是当 pkg 失败时,有哪些方法可以渲染 error.ejs
呢?
由于我已经在下面使用 .then()/.catch()
技术,我也可以在上面这样做吗?
换句话说,我可以嵌套 .then()/.catch()
语句吗?
我可以将外部代码包围在 try/catch
中(同时内部仍然有 try/catch
)吗?
最佳答案
pkg.impl_func()
似乎实现了典型的 Node.js 回调接口(interface)(即,如果发生错误,它会返回一个错误作为第一个参数,如果出现则返回 null
没有错误)。您可以简单地检查错误是否存在,并在出现错误时呈现 error.ejs
:
app.post('/aroute', function(req, res) {
pkg.impl_func(data, function (err, result) {
if (err) {
res.render('error.ejs');
} else {
myFunction(entity).then(user=>{
//DO_STUFF_HERE
res.render('page.ejs');
}).catch(err => {
console.log(err);
res.render('error.ejs');
});
}
});
});
或者,您可以使用util.promisify()
将 pkg.impl_func()
转换为异步函数。然后,您可以在 async
函数中使用 promise.catch()
或 try-catch
来简化语法:
const util = require('util')
const impl_func_async = util.promisify(pkg.impl_func)
// traditional promises:
app.post('/aroute', (req, res) => {
impl_func_async(data).then(result =>
return myFunction(entity)
}).then(user => {
// DO_STUFF_HERE
res.render('page.ejs')
}).catch(e => {
// Will catch thrown errors from impl_func_async and myFunction
console.log(e)
res.render('error.ejs')
})
})
// async-await:
app.post('/aroute', async (req, res) => {
try {
const result = await impl_func_async(data)
const user = await myFunction(entity)
// DO_STUFF_HERE
res.render('page.ejs')
} catch (e) {
// Will catch thrown errors from impl_func_async and myFunction
console.log(e)
res.render('error.ejs')
}
})
关于javascript - 使用 Javascript 和 Node.js 处理错误 (then/catch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58148895/