UNPKG

try-catch-cloud

Version:

Advanced error logging for your app with low code integration

221 lines (169 loc) 5.49 kB
# 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/ ```javascript 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: ```javascript 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. ```javascript 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 ```javascript 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 ```javascript 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 ```javascript // 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`, }; }; ```