npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

incepto

v1.0.0

Published

A package for inline asynchronous try-catch

Downloads

6

Readme

Incepto - Inline Try - Catch Clause for Async Functions

NPM

CircleCI

Installation

npm i incepto -s

Usage

const incepto = require("incepto");

// Latin Usage
async function myFunc() {
  const result = await incepto(throwableAsyncFunction()).capturam(
    "Function Failed"
  );
  return result;
}
// English Usage
async function myFunc() {
  const result = await incepto(throwableAsyncFunction()).catch(
    "Function Failed"
  );
  return result;
}
// If function throws, below line will throw an Error object with the "Function Failed" argument in construction
const result = await myFunc();

/**
 * 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 Usage
incepto.tracto = (e, message) => message;
// English Usage
incepto.errorHandler = (e, message) => 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
class HTTPException extends Error {
  constructor(code, message) {
    super(message);
    this.status = code;
    this.error = message;
  }
}
// Declare Verbose Error Code Packs
const NOT_FOUND = [404, "Not Found"];
// Set the Error Handler to throw an HTTPException and deconstruct the Error Code Pack
incepto.errorHandler = (e, ERROR) => throw new HTTPException(...ERROR);
// Override default error handler by extracting the status and error of the HTTPException and if it does not exist, assign default values
fastify.setErrorHandler(
  ({ status = 500, error = "Internal Server Error" }, req, reply) => {
    reply.status(status).send({ error });
  }
);
// Use incepto with asynchronous functions that might throw
fastify.get("/", async (req, res) => {
  const result = await incepto(throwableAsyncFunction()).catch(NOT_FOUND);
});
/**
 * 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.errorHandler = (e, ERROR) => {
  return { err: { message: ERROR, info: e } };
};
async function myAPI() {
  const result = await incepto(throwableAsyncFunction()).catch("Failed");
  return { data: result.data };
}
const { err, data } = await myAPI();
if (err !== undefined) {
  console.log(err.message);
  console.error(err.info);
}
// 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

Alex Papageorgiou

License

Licensed under GPLv3.