关于捕获错误的异步和等待和承诺

async and await and promise in regards to catching errors

我有一个关于在异步和等待中捕获用户错误的问题。

假设我有一个只为单个用户获取的路由。

routes.js

routes.get('/getuserbyid/:id', (req, res) => {

    const id = req.params.id;

    accountController.getById(id)
        .then((result) => {
            res.json({
                confirmation: 'success',
                result: result
            });
        })
        .catch((error) => {
            res.json({
                confirmation: 'failure',
                error: error
            });
        });
});

我有一个控制器可以获取请求。 accountController.js

export const getById = async (id) => {

        try {
            const user = await users.findOne({ where: {
                    id: id
                }});

            if (user === null) {
                return 'User does not exist';
            }
            return user;
        } catch (error) {
            return error;
        }
}

因此,无论发生什么情况,我都会得到空记录或单个记录。它仍然是成功的。 在承诺中,我可以拒绝 null,因此它会出现在路由的 catch 块中。现在有了异步和等待。我怎样才能在错误块中实现相同的空值?

export const getById = (id) => {

    return new Promise((resolve, reject) => {

        users.findOne({ where: {
            id: id
        }})
            .then((result) => {

                if (result === null) {
                    reject('User does not exit');
                }
                resolve(result);
            })
            .catch((error) => {
                reject(error);
            });
    });

}

如果您的值变为空,您可以抛出异常。

export const getById = async (id) => {
        const user = await users.findOne({ where: {
                id: id
            }});

        if (!user) {
            throw Error('User does not exist..');
        }
        return user;        
}

一个async函数总是returns一个Promise.

async 函数中使用 throw 构造会拒绝返回的 Promise

考虑

function getValue() {
  return Promise.reject(null);
}

getValue().catch(e => {
  console.log('An raised by `getValue` was caught by a using the `.catch` method');
  console.log(e);
});


(async function main() {
  try {
    await getValue();
  } catch (e) {
    console.log('An raised by `getValue` was caught by a catch block');
    console.log(e);
  }
}());

async function getValue() {
  throw null;
}

getValue().catch(e => {
  console.log('An raised by `getValue` was caught by a using the `.catch` method');
  console.log(e);
}); 

(async function main() {
  try {
    await getValue();
  } catch (e) {
    console.log('An raised by `getValue` was caught by a catch block');
    console.log(e);
  }
}());

异步方法中的 try 块处理 同步 异步错误。

考虑

function throws() {
  throw Error('synchronous failure');
}


async function rejects() {
  throw Error('asynchronous failure');
}

(async function main() {
  try {
    throws();
  } catch (e) {
    console.log('asynchronously handled', e.message);

  }

  try {
    await rejects();
  } catch (e) {
    console.log('asynchronously handled', e.message);
  }
}());

要记住的一个关键点是,如果您忘记 await 拒绝的承诺,异步错误将不会被捕获。这类似于在 .then.catch 回调

中忘记 return

首先,避免 Promise 反模式。您有一个 returns 一个 Promise 的函数,无需将其包装在 new Promise().

那么您的函数可能如下所示:

export const getById = (id) => {
  return users.findOne({ where: { id } })
    .then((user) => {
      if (user === null)
        throw 'User does not exit';

      return user;
    });
}

而这个的 async/await 版本是

export const getById = async (id) => {
  const user = await users.findOne({ where: { id } });

  if(user === null)
    throw 'User does not exist';

  return user;
}