javascript - 如何避免在 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当一个错误被捕获时,我仍然想得到通知这个错误来自哪个案例。
解决方案
将适配器改为由通道索引的对象,并在对象上查找通道属性:
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
}
推荐阅读
- javascript - 如何获取传单中多边形的上下文菜单?
- sharepoint - 无法连接到 sharepoint 2013 中的现有服务器场
- redux - 当我使用 getServerSideProp 它使持久存储不起作用
- javascript - 如何在此 video-js 播放器上添加自动自适应比特率选项
- ruby - 显示 bash 的 Ubuntu 终端:/home/vostro/.rvm/scripts/rvm:启动时没有这样的文件或目录
- javascript - 在一页上运行多个水平滚动
- vb.net - 如何在 Combobox 的 Select Change 事件中使用 DataGridView 复选框?
- java - Gradle 为具有 implementation 关键字的依赖项抛出 NoClassDefFoundError
- python - 如何根据值从字典中删除键?
- r - R中具有多个不同结果(命名包含数字)的线性回归