首页 > 解决方案 > 如何避免在 NodeJS 的 switch case 中重复 try/catch

问题描述

现在我的代码是这样的:

const androidChannel = "android";
const iosChannel = "ios";
const smsChannel = "sms";
const emailChannel = "email";

switch(channel) {
    case iosChannel:
        try{
            output = await apnsAdaptor.processRequest(notificationRequest)
            console.log(output);
        } catch(err) {
            console.log("IOS with err: " + err);
        } 
        break;
        
    case androidChannel:
        try{
            output = await androidAdaptor.processRequest(notificationRequest)
            console.log(output);
        } catch(err) {
            console.log("Android with err: " + err);
        }
        break;
    
    case smsChannel:
        try{
            output = await smsAdaptor.processRequest(notificationRequest)
            console.log(output);
        } catch(err) {
            console.log("Sms with err: " + err);
        }
        break;
    
    default:
        console.log("This is the defualt guy");
        break;
        
}

很明显,每种情况的结构都非常相似,包括对捕获的错误的处理。由于会添加更多案例,因此我希望避免多次重复 try/catch 结构。我想知道是否有更简洁的方式来写这个?

PS当一个错误被捕获时,我仍然想得到通知这个错误来自哪个案例。

标签: javascriptnode.js

解决方案


将适配器改为由通道索引的对象,并在对象上查找通道属性:

const adapters = {
  android: <theAndroidAdapter>,
  ios: <theIosAdapter>,
  // ...
};
// ...

const adapter = adapters[channelName];
if (adapter) {
  try {
    console.log(await adapter.processRequest(notificationRequest));
  } catch (err) {
    console.log(channelName + ' with err: ', err);
  }
} else {
  // no matching adapter
}

推荐阅读