javascript - 使用 Javascript 和 Node.js 处理错误 (then/catch)

标签 javascript node.js express error-handling try-catch

假设我在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/

相关文章:

javascript - 如何更有效地使用Ember中的适配器、序列化器、模型等工具?

node.js - Meteor 和 Socket IO 端口

javascript - 如何在GET方法中检查用户身份验证?

javascript - SQL 到 Mongo 事务架构

mysql - javascript中父级回调之前的多个嵌套回调函数

javascript - 将 pagespeed 与 phantomjs 和 jenkins 集成结合使用

javascript - 在 forEach 循环中设置每个单独循环的状态后如何拥有回调函数?

javascript - 为什么我的 SVG 功能的坐标在我更改时不是我想要的?

node.js - Sequelize reload() 清除所有模型数据

javascript - 使用 Node 中的 Q promise 库在值数组上顺序调用/执行相同的函数;并返回一个包含结果的新数组/集合