如何避免 NodeJS 中 switch case 中重复的 try/catch

Isa*_*odo 1 javascript node.js

现在我的代码是这样的:

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;
        
}
Run Code Online (Sandbox Code Playgroud)

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

PS 当一个错误被捕获时,我仍然希望得到通知这个错误来自哪种情况。

Cer*_*nce 9

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

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
}
Run Code Online (Sandbox Code Playgroud)