JSFiddle - React, Tailwind, and code Playground
by BaldEagle
JavaScript
"use strict"
/**
* MyError (sync) - descends from Error
* @param {string} inMsg - default null. Should be a string containing information
* about the error.
* Note: technique for extending Error from
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
* (below heading "Custom Error Types"), as observed Mon Sep 19, 2016
* and Tue Oct 18, 2016
* (the code example under that heading changed between those dates).
* http://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript,
* as observed Tue Oct 18, 2016. No mention of copyright restrictions noted.
*/
function MyError(inMsg = null) {
this.name = "MyError"
if (Object.prototype.toString.call(inMsg) === "[object String]" &&
inMsg.length > 0) {
this.message = inMsg
}
else { this.message = "MyError was called without a message." }
const lastPart = new Error().stack.match(/[^\s]+$/)
this.stack = `${ this.name } at ${ lastPart }`
}
MyError.prototype = Object.create(Error.prototype)
MyError.prototype.name = "MyError"
MyError.prototype.message = ""
MyError.prototype.constructor = MyError
MyError.prototype.toString = function() { return `${ this.name }: ${ this.message }` }
/**
* p and p1 - functions that demonstrate a behavior
* @param { number } n - integer
* @throw { LocError } - if n isn't an integer
*/
function p(n) {
if (!Number.isInteger(n)) { throw new MyError(`n must be an integer n=${ n }`) }
}
function p1(n) {
if (!Number.isInteger(n)) { throw new Error(`n must be an integer n=${ n }`) }
}
if (false) {
console.log(p(3))
console.log(p("t"))
}
else {
console.log(p1(3))
console.log(p1("t"))
}