try-catch-cloud
TypeScript icon, indicating that this package has built-in type declarations

1.0.54 • Public • Published

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`,
    };
};

Package Sidebar

Install

npm i try-catch-cloud

Weekly Downloads

147

Version

1.0.54

License

ISC

Unpacked Size

313 kB

Total Files

34

Last publish

Collaborators

  • oleksii_kilevoi
  • lemonardo
  • robert_pavlov