Errors, Exceptions in JavaScript

Working through a TypeScript issue. Note that fighting with typing in JavaScript is balanced on the wrong side for TypeScript it is overly strict without offering the immediacy type checking of a true static typed language like Java, C#, C++. In my opinion the correct balance is struct by Python which does type inference and optional type checking and hints and allows you to dial in the strictness.

Back to my point, is that I want to catch exceptions and errors from JavaScript code and funnel them into TypeScript methods.

For example say I have a common TypeScript method that looks like this

catchUnhandled(action: string, name?: string)

However this is going to be handled from code clients that look like this.

const err = new Error("it's bad");

and also

try {
  ...
} catch (ex) {
  <catchUnhandled>
}

In the above the majority of the cases will be of type DOMException but it could be anything so the type is any, never, unknown In this case the TypeScript option would be to use any for loose handling and never to turn off checking. Unknown works, but passes the problem on to the caller method internals though.

Back to the consolidated handling of Error, DOMException both have properties of name and message so I would like to use those properties.

From the Error object above

Error: it's bad
    at <anonymous>:1:13

err.name
'Error'
err["name"]
'Error'
err.ohno
undefined
err["ohno"]
undefined
err.hasOwnProperty("ohno")
false
err.hasOwnProperty("name")
false

Now compare to DOMException const exc = new DOMException("oh no", "bad")

const exc = new DOMException("oh no", "bad")

exc.name
'bad'
exc["name"]
'bad'
exc.ohno
undefined
exc["ohno"]
undefined
exc.hasOwnProperty("ohno")
false
exc.hasOwnProperty("name")
false

Therefore need to do this to pull out the details

Object.assign({}, { action: null, name: null }, { action: err["message"] || null, name: err["name"] || null });

{action: "it's bad", name: 'Error'}

Object.assign({}, { action: null, name: null }, { action: exc["message"] || null, name: exc["name"] || null });

{action: 'oh no', name: 'bad'}

Using the bracket notation instead of using hasOwnProperty normally I would use that but it is not behaving as I would expect and it's because that only checks the direct object in this case Error and DOMException are inheriting the properties is why.