How to avoid duplicated try/catch in switch case in NodeJS

Right now my code is like this:

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;
        
}

It’s clear that the structures for each case are quite similar, including the handling of catched error. Since there will be more cases added, I would like to avoid repeating the try/catch structure so many times. I wonder if there’s a more succinct way to write this?

P.S. When an error is caught, I still would like to get notified which case this error is from.

40 thoughts on “How to avoid duplicated try/catch in switch case in NodeJS”

Leave a Comment