{"id":571,"hash":"b61fc31922be84e6c5e41ce1e4a9e9f3c1b69d6e093e67e931e4bce9c617e7aa","pattern":"Extending Error in Javascript with ES6 syntax &amp; Babel","full_message":"I am trying to extend Error with ES6 and Babel. It isn't working out.\n\nclass MyError extends Error {\n  constructor(m) {\n    super(m);\n  }\n}\n\nvar error = new Error(\"ll\");\nvar myerror = new MyError(\"ll\");\nconsole.log(error.message) //shows up correctly\nconsole.log(myerror.message) //shows empty string\n\nThe Error object never get the right message set.\n\nTry in Babel REPL.\n\nNow I have seen a few solutions on SO (for example here), but they all seem very un-ES6-y. How to do it in a nice, ES6 way? (That is working in Babel)","ecosystem":"npm","package_name":"ecmascript-6","package_version":null,"solution":"Based on Karel Bílek's answer, I'd make a small change to the constructor:\n\nclass ExtendableError extends Error {\n  constructor(message) {\n    super(message);\n    this.name = this.constructor.name;\n    if (typeof Error.captureStackTrace === 'function') {\n      Error.captureStackTrace(this, this.constructor);\n    } else { \n      this.stack = (new Error(message)).stack; \n    }\n  }\n}    \n\n// now I can extend\n\nclass MyError extends ExtendableError {}\n\nvar myerror = new MyError(\"ll\");\nconsole.log(myerror.message);\nconsole.log(myerror instanceof Error);\nconsole.log(myerror.name);\nconsole.log(myerror.stack);\n\nThis will print MyError in the stack, and not the generic Error.\n\nIt will also add the error message to the stack trace - which was missing from Karel's example.\n\nIt will also use captureStackTrace if it's available.\n\nWith Babel 6, you need transform-builtin-extend (npm) for this to work.","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/31089801/extending-error-in-javascript-with-es6-syntax-babel","votes":140,"created_at":"2026-04-19T04:51:22.569639+00:00","updated_at":"2026-04-19T04:51:22.569639+00:00"}