Specific Exception Handling

One problem is that some platforms/libraries use special properties on the error object instead of subclasses to make different error types (like node), so you would also need to provide a way to support them too. I had previously proposed providing a standard exception class to Javascript, which if used would make this kind of feature more palatable. The consensus in that proposal is that the design I came us with would probably break backwards compatibility, but it could still be possible to get everyone to use a standard system through a protocol, i.e. if an exception provided a unique key to a Symbol.exceptionType property (or just a non-symbol "code" property), and the catch clause would could check against a key. For example:

DOMException[Symbol.exceptionType] = 'DOM:DOMException'
try {
  doSomeDomOperation()
} catch 'DOM:DOMException' (ex) { 
  console.log('A DOM exception was thrown!')
}

If we don't get everyone onto a standard, then your catch handler would need to be flexible enough to handle exception subtypes and unique properties on the error object. Here's one possibility:

const isSubType = type => ex => ex instanceof type
const hasProperty = (key, value) => ex => ex[key] === value

try {
  ...
} catch where isSubType(DOMException) {
  ...
} catch where hasProperty('code', 'FileNotFound') {
  ...
}
1 Like