Proper use of errors

后端 未结 4 710
悲&欢浪女
悲&欢浪女 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:18

    The convention for out of range in JavaScript is using RangeError. To check the type use if / else + instanceof starting at the most specific to the most generic

    try {
        throw new RangeError();
    }
    catch (e){
        if (e instanceof RangeError){
            console.log('out of range');
        } else { 
            throw; 
        }
    }
    

提交回复
热议问题