Incepto - Inline Try - Catch Clause for Async Functions
Installation
npm i incepto -s
Usage
const incepto = ; // Latin Usage { const result = await ; return result;}// English Usage { const result = await ; return result;}// If function throws, below line will throw an Error object with the "Function Failed" argument in constructionconst result = await ; /** * We can override the error handler and provide alternative behaviour. * The error handler takes two arguments as input, the actual error in * the first element and the custom message or object passed to "catch" * in the second element. */// Latin Usageincepto message;// English Usageincepto message; /** * For instance, asynchronous servers can benefit from this package * such as fastify by creating a custom error handler and creating * a custom Error object in the error handler. */// Custom Error Class { supermessage; thisstatus = code; thiserror = message; }// Declare Verbose Error Code Packsconst NOT_FOUND = 404 "Not Found";// Set the Error Handler to throw an HTTPException and deconstruct the Error Code Packincepto throw ...ERROR;// Override default error handler by extracting the status and error of the HTTPException and if it does not exist, assign default valuesfastify;// Use incepto with asynchronous functions that might throwfastify;/** * Another use case for the library, apart from cleaner code, * is its usage within libraries to return an err variable * wherever the code throws. */incepto { return err: message: ERROR info: e ;}; { const result = await ; return data: resultdata ;}const err data = await ;if err !== undefined console; console;// Continue Execution
Description
This plugin introduces an inline try-catch approach. While the name try
would be more preferable, it is a reserved keyword and attempt
was taken on npm
so I chose to name it incepto
after the latin translation of "attempt".
It takes a Promise
as input (async
functions by default return a Promise
when invoked) and, after calling catch
, capture
or capturam
("catch" in latin) with what you wish to pass to the error handler or throw via the default behavior, it attempts to resolve the Promise
and on failure executes its error handler.
The default behaviour is to throw
with what was passed in catch
etc. as in the following line:
throw new Error(catchInput);
Options
You can override the default throw
behaviour by overriding the errorHandler
or tracto
("handler" in, you guessed it, latin) variable of the function object. With it, you can choose to return a value, throw a specific type of error or whichever you basically wish.
Author
License
Licensed under GPLv3.