Inheriting from the Error object - where is the message property?

前端 未结 7 1213
面向向阳花
面向向阳花 2020-11-30 02:58

I noticed a strange behavior while defining custom error objects in Javascript:

function MyError(msg) {
    Error.call(this, msg);
    this.name = \"MyError\         


        
7条回答
  •  一生所求
    2020-11-30 03:46

    What's wrong with doing it this way in ES6?

    class MyError extends Error {
        constructor(message) {
            super(message);
            // Maintains proper stack trace (only on V8)
            if (Error.captureStackTrace) {
                Error.captureStackTrace(this, MyError);
            }
            this.appcode= 123; // can add custom props
        }
    }
    

提交回复
热议问题