Proper use of errors

后端 未结 4 705
悲&欢浪女
悲&欢浪女 2021-01-29 19:50

I\'m using TypeScript for a reasonably large project, and am wondering what the standard is for the use of Errors. For example, say I hand an index out of bounds ex

4条回答
  •  星月不相逢
    2021-01-29 20:39

    Simple solution to emit and show message by Exception.

    try {
      throw new TypeError("Error message");
    }
    catch (e){
      console.log((e).message);//conversion to Error type
    }
    

    Caution

    Above is not a solution if we don't know what kind of error can be emitted from the block. In such cases type guards should be used and proper handling for proper error should be done - take a look on @Moriarty answer.

提交回复
热议问题