这是在JS中的依赖函数中将Try-Catch与async-wait一起使用的正确方法吗?

时间:2019-09-08 04:28:40

标签: javascript node.js async-await try-catch

这些是我的以下代码文件。

flamesHelper.js

import flames from "../model/flames";

async function count(query = {}) {
  try {
    return await flames.count(query).exec();
  } catch (error) {
    return new Error(error);
  }
}

flamesController.js

import flamesHelper from "../helpers/flamesHelper";
const flamePerPage = 100;

async function count(req, res) {
  try {
    const count = await flamesHelper.count();
    return res.status(200).send({ count, flamePerPage });
  } catch (error) {
    console.log(error);
    return res.status(500).send({ message: "Error while counting flames." });
  }
}

flames.js

import express from "express";
const router = express.Router();
import flamesController from "../controllers/flamesController";

router.get("/getCount", loginUtil.isLoggedIn, flamesController.count);

这是一个简单的NodeJS代码。我需要帮助以了解我的代码是否正确。 代码工作正常,我得到正确的计数。我可能会在整个项目中使用相同的结构。

但是我的问题是

如果在flamesHelper.count的任何时间发生任何错误,将通过flamesController.count方法捕获。 另外,如果您能告诉我,这是将async-awaittry-catch一起使用的正确方法,其中涉及到使用 Mongodb mongoose

谢谢你!

2 个答案:

答案 0 :(得分:2)

对于您打算做的事情(根据您的评论),您可以执行以下操作:

function count(query = {}) {
    return flames.count(query).exec();
}

这将只返回诺言,然后返回的诺言将解决或拒绝。无需对显示的简单代码使用await

并且,根据您的问题,如果您希望错误仍然是被拒绝的承诺,则您将不得不throw err或返回Promise.reject(err)return new Error(...)会将错误对象作为已解决的值来做出已解决的承诺,而这几乎是您所不需要的。

答案 1 :(得分:1)

如果要自定义数据库异常并将映射的错误返回给控制器,则可以在flamesHelper.js中使用try catch块。

flamesHelper.js

import flames from "../model/flames";

     async function count(query = {}) {
       try {
           return await flames.count(query).exec();
          } catch (error) {
            throw Error('Unable to count flames');

         // Or check db errors and map each error to user friendly error
         }
        }

flamesController.js

        import flamesHelper from "../helpers/flamesHelper";
        const flameDetailsPerPage = 100;

       async function count(req, res) {
           try {
                    const count = await flamesHelper.count();
                    return res.status(200).send({ count, flamePerPage });
           } catch (error) {
                 console.log(error);
                // Return mapped error.
                return res.status(500).send({ message: error.message });
            }
         }

在您的情况下,您将抛出相同的错误,因此无需尝试在helper.js中捕获块,只是返回了查询结果,如果有任何错误,您将在控制器中捕获它。

  async function count(query = {}) {

       return flames.count(query).exec();

     }

并保持控制器不变。

相关问题