Skip to content

Commit

Permalink
edge-api-sdk: better error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
joshbalfour committed Apr 12, 2024
1 parent 8149e14 commit 7155a9f
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 15 deletions.
2 changes: 1 addition & 1 deletion packages/modules/edge-api-sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"main": "dist/index.js",
"types": "dist/index.d.ts",
"description": "Provides convenience wrappers for accepting and responding to [@reapit-cdk/edge-api]('../../constructs/edge-api/readme.md') lambda requests.",
"version": "0.0.20",
"version": "0.0.21",
"homepage": "https://github.com/reapit/ts-cdk-constructs/blob/main/packages/modules/edge-api-sdk",
"readme": "https://github.com/reapit/ts-cdk-constructs/blob/main/packages/modules/edge-api-sdk/readme.md",
"bugs": {
Expand Down
17 changes: 5 additions & 12 deletions packages/modules/edge-api-sdk/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,17 +75,6 @@ export const consoleTransport = (payload: MinimalLogPayload | LogPayload) => {
console.log(JSON.stringify(scrub(payload)))
}

type AdditionalLogData = {
error: Error
}

const isAdditionalLogData = (thing: any): thing is AdditionalLogData => {
if (typeof thing === 'object' && thing.error && typeof thing.error === 'object' && thing.error.name) {
return true
}
return false
}

export const panic = (error: Error, event: EventInput) => {
const { AWS_REGION, AWS_LAMBDA_FUNCTION_NAME, AWS_LAMBDA_FUNCTION_VERSION } = process.env
const payload: MinimalLogPayload = {
Expand Down Expand Up @@ -123,6 +112,10 @@ export type LoggerConfig = {
noConsole?: boolean
}

const isError = (arg: any): arg is Error => {
return typeof arg === 'object' && typeof arg.name === 'string'
}

export class Logger {
private request: RCRequest<any>
private entries: LogEntry[] = []
Expand All @@ -144,7 +137,7 @@ export class Logger {
level,
message: format(...args),
timestamp: new Date(),
error: stringifiableError(args.find(isAdditionalLogData)?.error),
error: args.find(isError),
})
const centralize = level === 'error' || level === 'critical' || level === 'panic'
if (centralize) {
Expand Down
2 changes: 1 addition & 1 deletion packages/modules/edge-api-sdk/tests/edge-api-sdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ const generateApiGatewayRequest = ({
}
}

const generateCloudfrontRequest = ({
export const generateCloudfrontRequest = ({
headers = {
host: [{ key: 'host', value: 'google.com' }],
},
Expand Down
42 changes: 41 additions & 1 deletion packages/modules/edge-api-sdk/tests/sentry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import { enableFetchMocks } from 'jest-fetch-mock'
import fetchMock from 'jest-fetch-mock'
enableFetchMocks()

import { JSONRequest } from '../src'
import { JSONRequest, jsonRequestHandler } from '../src'
import { init } from '../src/sentry/sentry'
import { generateCloudfrontRequest } from './logger.test'
import { LogEntry, LogPayload } from '../src/logger'
import { Event } from '@sentry/types'

process.env.AWS_REGION = 'eu-west-2'

const generateLogPayload = (entries: LogEntry[]): LogPayload => {
const event = generateCloudfrontRequest({})
const request: JSONRequest<any, any> = {
Expand Down Expand Up @@ -152,3 +154,41 @@ describe('sentry logger transport', () => {
})
})
})

describe('sentry in edge-api-sdk', () => {
beforeEach(() => {
fetchMock.resetMocks()
})

it('should send unhandled errors to sentry', async () => {
const handler = jest.fn().mockRejectedValue(new Error('error message'))
const env = {
sentryDsn: 'https://asdf@qwerty.ingest.sentry.io/123456',
sentryRelease: 'localhost',
}

await jsonRequestHandler<any>(handler, (request) => ({
loggerConfig: {
transports: [init(request)],
},
}))(
generateCloudfrontRequest({
uri: '/',
env,
body: JSON.stringify({ something: 'here' }),
}),
{} as any,
)

expect(fetchMock).toBeCalledTimes(1)

const [, reqInit] = fetchMock.mock.calls[0]
const [, , event] = (reqInit?.body as string)?.split('\n').map((str) => JSON.parse(str)) ?? []
const ev = event as Event

expect(ev).toHaveProperty('exception')
const values = ev?.exception?.values
expect(values?.[0].type).toEqual('Error')
expect(values?.[0].value).toEqual('error message')
})
})

0 comments on commit 7155a9f

Please sign in to comment.