Multiple catch in javascript

后端 未结 4 960
清歌不尽
清歌不尽 2021-01-04 00:34

Is it possible to use multiple catch in JS(ES5 or ES6) like I describe below (it is only example):

try {
­­­­  // just an error
  throw 1; 
}
ca         


        
4条回答
  •  抹茶落季
    2021-01-04 01:27

    There is absolutely nothing wrong with multiple if/then/else of course, but I never liked the look of it. I find that my eyes skim a bit faster with everything lined up, so I use the switch approach instead to help me skim/seek to the correct block. I've also started using a lexical scope {} to enclose case blocks now that the ES6 let command has gained popularity.

    try {
    
      // OOPS!
    
    } catch (error) {
    
      switch (true) {
        case (error instanceof ForbiddenError): {
          // be mean and gruff; 
          break;
        }
        case (error instanceof UserError): {
          // be nice; 
          break;
        }
        default: {
          // log, cuz this is weird;
        }
      }
    
    }
    

提交回复
热议问题