Last active
February 16, 2019 15:51
-
-
Save caalberts/50935723d1fabf5f2bb78d533573e5ed to your computer and use it in GitHub Desktop.
Attempt to handle errors in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Todo: improve DSL with a “.with()”