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

try-catch-cloud

v1.0.54

Published

Advanced error logging for your app with low code integration

Downloads

736

Readme

Try Catch Cloud

This package helps with error tracking and monitoring for your Node.js applications with a minimum of effort.

Usage

Note: You can get API key on https://try-catch-cloud-fe.pages.dev/

import { ErrorUtility } from "try-catch-cloud";

// Change your-project-name to actual project name.
// Change your-api-key with API key from our website.
// Error logs will be associated with your project name and stored, referencing it.
const errorTrack = new ErrorUtility("your-project-name", "your-api-key");

try {
	...
} catch (error) {
    const context = { userId: '...', foo: 'bar' };
	await errorTrack.sendError(error, context);
}

The following approach lets you manually set all necessary request information regardless of what framework you use:

app.use((err, req, res, next) => {
    const { base64File, ...body } = req.body;
    errorTrack.sendErrorFromEndpoint(
        error,
        {
            url: req.originalUrl.split("?")[0],
            method: req.method,
            headers: req.headers,
            query: req.query,
            body,
        },
        { ...context }
    );
});

Middlewares

Express

Since Express 4.x.x (and older versions) does not pass errors occurring in async route handlers to error handlers, you must manually catch these errors using a try-catch block and pass them to the next function. Alternatively, you can use express-async-handler or a similar library to address this issue.

import { setupTryCatch, setContext } from 'try-catch-cloud/express';
import asyncHandler from 'express-async-handler';

// Create try-catch instance
const tryCatch = setupTryCatch({
    projectName: "your-project-name",
    apiKey: "your-api-key",
});

// Use `initialize` before other handlers
app.use(tryCatch.initialize);

app.get("/", (req, res) => {
    // Enhance error details with contextual information
    setContext(req, { message: req.query.message });

    ...

    res.json({ message: 'ok' });
});

app.get("/hello", asyncHandler(async (req, res) => {
    // Enhance error details with contextual information
    setContext(req, { message: req.query.message });

    ...

    res.json({ message: 'ok' });
}));

// Put `onError` after all controllers and before error handlers
app.use(tryCatch.onError);

// You can add custom error handler
app.use((error, req, res, next) => {
    res.status(500).json({ message: 'Internal server error' }).end();
});

Hono

import { tryCatch } from "try-catch-cloud/hono";

// Initialize tryCatch
app.use(
    tryCatch({
        projectName: "your-project-name",
        apiKey: "your-api-key",
    })
);

app.get("/:message", (c) => {
    // Enhance error details with contextual information
    c.get('tryCatch').setContext({ message: c.req.param('message') });

    ...

    return c.json({ message: 'ok' });
});

// Optionally add custom error handler
app.onError((e, c) => {
    c.get("tryCatch").setContext({
        userId: "...",
    });

    return c.json({ message: "Internal server error" }, 500);
});

Cloudflare Workers

import { CloudflareErrorUtility } from 'try-catch-cloud/cloudflare-workers';

const tryCatchCloud = new CloudflareErrorUtility(PROJECT_NAME, API_KEY);

export default {
    async fetch(request, env, ctx) {
        try {
            // Your code here
        } catch (e) {
            const url = new URL(request.url);

            ctx.waitUntil(
                errorUtility.sendErrorFromEndPoint(e,
                    {
                        method: request.method,
                        url: url.pathname,
                        body: await request.json(),
                        query: Object.fromEntries(url.searchParams.entries()),
                        headers: Object.fromEntries(request.headers.entries()),
                    },
                    { userId: '...' }
                )
            );

            return Response.json({ message: 'Internal server error' }, { status: 500 });
        }
    }
} satisfies ExportedHandler;

// Hono

app.onError(async (err, c) => {
	if (err instanceof HTTPException) {
		return err.getResponse();
	}

	c.executionCtx.waitUntil(errorUtility.sendErrorFromEndPoint(err, {
        method: c.req.method,
        url: c.req.url,
        body: await c.req.json(),
        query: c.req.query(),
        headers: c.req.header(),
    }, { test: 'hono-cf' }));

	return c.json({
		message: 'Internal server error',
	});
});

AWS Lambda


// With middy
import { addContext, tryCatch } from "try-catch-cloud/lambda";

const rawHandler: APIGatewayProxyHandlerV2 = async (event) => {
    addContext({ userId: '...' });
    // your code here

    return {
        statusCode: 200,
        body: `Hello world`,
    };
};

export const handler = middy(rawHandler)
    .use(tryCatch({
        projectName: 'PROJECT_NAME',
        apiKey: 'API_KEY',
    }));

// Without middy

import { LambdaErrorUtility } from "try-catch-cloud/lambda";

const tryCatch = new LambdaErrorUtility('PROJECT_NAME', 'API_KEY');

const rawHandler: APIGatewayProxyHandlerV2 = async (event) => {
    try {
        // your code here
    } catch (e) {
        await tryCatch.sendErrorFromEndPoint(e, event, { userId: '...' });

        return {
            statusCode: 500,
            body: 'Internal server error',
        }
    }

    return {
        statusCode: 200,
        body: `Hello world`,
    };
};