maybe-try 🙈
A declarative sync & async js maybe that notes something may fail
Node and Browser Compatible
View on NPM
npm install maybe-try
Usage
The module exposes 3 methods, one for synchronous operations, one for promises, and one for callbacks.
Each method takes 2 parameters, the fallbackValue for error scenarios, and a function.
Both parameters are REQUIRED, maybe-try does not supply a default value for you
Returns an object with caught errors (if any) and either the result or fallbackValue, depending on success
More in-depth examples can be found here
Synchronous Version
const maybeTry = ; // Synchronous Version const data = 'some string';const error result = maybeTry;// No need to run try/catches in your code blocks, maybeTry resolves the caught error and result with assignment
Promise Version
// Promise Version { const fallbackValue = rating: 5 ; return maybeTry ;}
Callback Version
// Callback Version const cbFallbackValue = name: 'Tom' ;;
Registering an errorHandler
An optional feature to register a function to handle errors for all occurances within the module
It's useful if you'd like to only stick to the happy path with your application logic but send logs to an external service when errors do occur
It should be noted that the errorHandler is a fire and forget method. You cannot chain to it or call it explicitly.
Example using the Syncronous Version
const errorHandler = { const message = error; console; ;}; maybeTry; // The API remains the same, but the errorHandler will be firing in the backgroundconst data = 'some string';const error result = maybeTry;// at this point, logErrorsToAnExternalService() has been called