I am trying to extend Error with ES6 and Babel. It isn\'t working out.
class MyError extends Error {
constructor(m) {
super(m);
}
}
var error = new
I improved a little the solution of @Lee Benson this way:
extendableError.js
class ExtendableError extends Error {
constructor(message, errorCode) {
super(message);
this.name = this.constructor.name;
this.errorCode = errorCode
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = (new Error(message)).stack;
}
}
}
export default ExtendableError
an example of an error
import ExtendableError from './ExtendableError'
const AuthorizationErrors = {
NOT_AUTHORIZED: 401,
BAD_PROFILE_TYPE: 402,
ROLE_NOT_ATTRIBUTED: 403
}
class AuthorizationError extends ExtendableError {
static errors = AuthorizationErrors
}
export default AuthorizationError
Then you are able to group errors while having option specifiers to decide what to do differently in some of your application specific situations
new AuthorizationError ("The user must be a seller to be able to do a discount", AuthorizationError.errors.BAD_PROFILE_TYPE )
As @sukima mentions, you cannot extend native JS. The OP's question cannot be answered.
Similar to Melbourne2991's answer, I did used a factory rather, but followed MDN's recommendation for customer error types.
function extendError(className){
function CustomError(message){
this.name = className;
this.message = message;
this.stack = new Error().stack; // Optional
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;
return CustomError;
}