Skip to content

Instantly share code, notes, and snippets.

@caalberts
Last active February 16, 2019 15:51
Show Gist options
  • Save caalberts/50935723d1fabf5f2bb78d533573e5ed to your computer and use it in GitHub Desktop.
Save caalberts/50935723d1fabf5f2bb78d533573e5ed to your computer and use it in GitHub Desktop.
Attempt to handle errors in JS
// specifically creates a closure to handle specific error class with a given error handler
// it rethrows all other errors
const specifically = (errorClass) => (errHandler) => (err) => {
if (err instanceof errorClass) {
return errHandler(err)
}
throw err
}
// example usage
class ArgumentError extends Error {}
class SystemError extends Error {}
class UnhandledError extends Error {}
const argErrorHandler = (err) => {
console.log('handled ArgumentError: ', err.message)
}
const systemErrorHandler = (err) => {
console.log('handled SystemError: ', err.message)
}
const testFunc = async (errorClass, message) => {
throw new errorClass(message)
}
// this is handled
testFunc(ArgumentError, 'bad argument').
catch(specifically(SystemError)(systemErrorHandler)).
catch(specifically(ArgumentError)(argErrorHandler))
// this is handled
testFunc(SystemError, 'system failure').
catch(specifically(SystemError)(systemErrorHandler)).
catch(specifically(ArgumentError)(argErrorHandler))
// this is not handled
testFunc(UnhandledError, 'BOOM!').
catch(specifically(SystemError)(systemErrorHandler)).
catch(specifically(ArgumentError)(argErrorHandler))
@caalberts
Copy link
Author

Todo: improve DSL with a “.with()”

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment