Javascript exceptions

From wikinotes
Revision as of 15:00, 6 June 2021 by Will (talk | contribs) (→‎Custom Errors)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Documentation

MDN: control flow and error handling https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling
MDN: error types https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

Basics

try {
    throw new TypeError("expected Integer")
} catch(err) {
    if (err instanceOf EvalError) {
        // ...
    } else if (err instanceOf RangeError) {
        // ...
    }
} finally {

}

Custom Errors

You can throw any type of object that you like (Object, String, ...) in javascript.
but if you'd like to obtain stracktraces and for the object to be typed as an error:

ecmascript 6+ (w/o transpiler)


class CustomError extends Error { /* ... */}


ecmascript <6


stack-overflow

// source:  https://stackoverflow.com/questions/464359/custom-exception-type
function InvalidArgumentException(message) {
    this.message = message;
    // Use V8's native method if available, otherwise fallback
    if ("captureStackTrace" in Error)
        Error.captureStackTrace(this, InvalidArgumentException);
    else
        this.stack = (new Error()).stack;
}

InvalidArgumentException.prototype = Object.create(Error.prototype);
InvalidArgumentException.prototype.name = "InvalidArgumentException";
InvalidArgumentException.prototype.constructor = InvalidArgumentException;

MDN

function CustomError(message, fileName, lineNumber) {
  var instance = new Error(message, fileName, lineNumber);
  instance.name = 'CustomError';
  Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
  if (Error.captureStackTrace) {
    Error.captureStackTrace(instance, CustomError);
  }
  return instance;
}

CustomError.prototype = Object.create(
  Error.prototype, {
    constructor: {
      value: Error,
      enumerable: false,
      writable: true,
      configurable: true
    }
  }
);

if (Object.setPrototypeOf){
  Object.setPrototypeOf(CustomError, Error);
} else {
  CustomError.__proto__ = Error;
}