toucan-js
toucan-js copied to clipboard
Allow instantiating Toucan before the request arrives
Hello again.
So I've using Toucan for a while in a couple of Cloudflare Workers projects now and have been wondering if we could change it so that I could instantiate the instance only once in the global context and reuse it for every request, like this:
type Handler = (req: Request) => Response | Promise<Response>;
declare const SENTRY_DSN: string;
const sentry = new Toucan({ dsn: SENTRY_DSN });
async function catchErrors(event: FetchEvent, handler: Handler): Promise<Response> {
try {
return await handler(event.request);
} catch (err) {
sentry.captureException(err, event);
return new Response(null, { status: 500 });
}
}
Of course, this would be a breaking change, so another idea I had was to make an extends method:
type Handler = (req: Request) => Response | Promise<Response>;
declare const SENTRY_DSN: string;
const baseSentry = new Toucan({ dsn: SENTRY_DSN });
async function catchErrors(event: FetchEvent, handler: Handler): Promise<Response> {
const sentry = baseSentry.extend({ event });
try {
return await handler(event.request);
} catch (err) {
sentry.captureException(err, event);
return new Response(null, { status: 500 });
}
}
These ways we could define defaults and avoid instantiating extra objects at every request, but since Toucan's constructor requires the FetchEvent, neither of these options are possible right now.