Proper use of errors

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

    Don't forget about switch statements:

    • Ensure handling with default.
    • instanceof can match on superclass.
    • ES6 constructor will match on the exact class.
    • Easier to read.

    function handleError() {
        try {
            throw new RangeError();
        }
        catch (e) {
            switch (e.constructor) {
                case Error:      return console.log('generic');
                case RangeError: return console.log('range');
                default:         return console.log('unknown');
            }
        }
    }
    
    handleError();

提交回复
热议问题