|
| 1 | +import type { IntegrationFn } from '@sentry/core'; |
| 2 | +import { captureException, debug, defineIntegration, getClient } from '@sentry/core'; |
| 3 | +import { DEBUG_BUILD } from '../debug-build'; |
| 4 | + |
| 5 | +const INTEGRATION_NAME = 'Hono'; |
| 6 | + |
| 7 | +interface HonoError extends Error { |
| 8 | + status?: number; |
| 9 | +} |
| 10 | + |
| 11 | +export interface Options { |
| 12 | + /** |
| 13 | + * Callback method deciding whether error should be captured and sent to Sentry |
| 14 | + * @param error Captured middleware error |
| 15 | + */ |
| 16 | + shouldHandleError?(this: void, error: HonoError): boolean; |
| 17 | +} |
| 18 | + |
| 19 | +/** Only exported for internal use */ |
| 20 | +export function getHonoIntegration(): ReturnType<typeof _honoIntegration> | undefined { |
| 21 | + const client = getClient(); |
| 22 | + if (!client) { |
| 23 | + return undefined; |
| 24 | + } else { |
| 25 | + return client.getIntegrationByName(_honoIntegration.name); |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +// todo: implement this |
| 30 | +function isHonoError(err: unknown): err is HonoError { |
| 31 | + // @ts-ignore |
| 32 | + return 'status' in err; |
| 33 | +} |
| 34 | + |
| 35 | +const _honoIntegration = ((options: Partial<Options> = {}) => { |
| 36 | + let _shouldHandleError: (error: Error) => boolean; |
| 37 | + |
| 38 | + return { |
| 39 | + name: INTEGRATION_NAME, |
| 40 | + setupOnce() { |
| 41 | + _shouldHandleError = options.shouldHandleError || defaultShouldHandleError; |
| 42 | + }, |
| 43 | + handleHonoException(err: HonoError): void { |
| 44 | + if (!isHonoError) { |
| 45 | + DEBUG_BUILD && debug.log('Hono integration could not detect a Hono error'); |
| 46 | + return; |
| 47 | + } |
| 48 | + if (_shouldHandleError(err)) { |
| 49 | + captureException(err, { mechanism: { handled: false, type: 'auto.faas.cloudflare.error_handler' } }); |
| 50 | + } |
| 51 | + }, |
| 52 | + }; |
| 53 | +}) satisfies IntegrationFn; |
| 54 | + |
| 55 | +/** |
| 56 | + * Automatically captures exceptions caught with the `onError` handler in Hono. |
| 57 | + * |
| 58 | + * The integration is added by default. |
| 59 | + */ |
| 60 | +export const honoIntegration = defineIntegration(_honoIntegration); |
| 61 | + |
| 62 | +/** |
| 63 | + * Default function to determine if an error should be sent to Sentry |
| 64 | + * |
| 65 | + * 3xx and 4xx errors are not sent by default. |
| 66 | + */ |
| 67 | +function defaultShouldHandleError(error: HonoError): boolean { |
| 68 | + // todo: add test for checking error without status |
| 69 | + const statusCode = error?.status; |
| 70 | + // 3xx and 4xx errors are not sent by default. |
| 71 | + return statusCode ? statusCode >= 500 || statusCode <= 299 : true; |
| 72 | +} |
0 commit comments