Created
May 18, 2011 16:50
-
-
Save cameronhunter/978987 to your computer and use it in GitHub Desktop.
I've always liked Ruby's "rescue" keyword. I've implemented something similar in Javascript.
This file contains hidden or 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
rescue = do(console) -> | |
(expression, fallback) -> | |
try expression?() || expression | |
catch e | |
console?.warn?( 'Rescued from', e, '. Using fallback value', fallback ) | |
return fallback |
This file contains hidden or 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
/* | |
* USAGE | |
*/ | |
var riskyValue = rescue( function() { throw new Error("oh no!"); }, "All ok!" ); | |
console.assert( riskyValue === "All ok!" ); |
This file contains hidden or 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
var rescue = (function(console) { | |
return function(expression, fallback) { | |
try { | |
return (typeof expression === "function" ? expression() : void 0) || expression; | |
} catch (e) { | |
if (console != null && typeof console.warn === "function") | |
console.warn('Rescued from', e, '. Using fallback value', fallback); | |
return fallback; | |
} | |
}; | |
})(console); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment