try/catch 块中的多个依赖 API 调用? (节点)

Multiple, dependent API calls in try/catch block? (NodeJS)

我想知道如何使用 try catch 块在 nodejs 中最好地处理多个依赖 API 调用。假设我需要发送请求,等待响应,然后在随后的 API 请求中使用响应到不同的服务器等等。我最初尝试将它们分成几个 try/catch 块,但后来意识到,如果我依赖于响应,我就无法真正将后续请求分开。

这是我的意思的一个例子:

try {
      const token = await getAuth0Token();
      const userExistsInAuth0 = await doesUserExist({
        email,
        token
      });

      if (!userExistsInAuth0) {
        return res.status(500).json({
          //...
        });
      }

      // Create User
      let createUserStatus = await createUser({
         //....
      });

      if (createUserStatus == 'error') {
        return res.status(200).json({
            //...
        });
      }

      const payment = await stripe.paymentIntents.create({
        //...
      });

      return res.status(200).json({ //Success
         //...
      });
    } catch (error) {    
      return res.status(500).json({ //Error
         //...
      });
    }

这是解决此问题的推荐方法吗?我担心它很快就会变得很乱,但我不明白我怎么能把东西分开。

您可以定义自定义错误-类 并在您的服务中抛出这些 类 的实例。然后在现有的 catch 块中处理这些错误。例如:

class UserNotFound extends Error { ... }
class CreateUserError extends Error { ... }
// etc.

然后在你的 catch 块中你可以使用 instanceof 来确定错误:

try {
      const token = await getAuth0Token();
      // doesUserExist now throws an UserNotFound error if the user does not exist yet
      const userExistsInAuth0 = await doesUserExist({
        email,
        token
      });     

      // Create User
      let createUserStatus = await createUser({
         //....
      });     

      const payment = await stripe.paymentIntents.create({
        //...
      });

      return res.status(200).json({ //Success
         //...
      });
    } catch (error) {  
      if (error instance of UserNotFound) { // handle UserNotFound error 
      } else if(error instance of CreateUserError) { // handle CreateUserError error
      } else {
        // handle any unhandled error
        return res.status(500).json({ //Error
         //...
       });
      }
    }