diff --git a/packages/node/src/integrations/context.ts b/packages/node/src/integrations/context.ts index 73fa8fa40c03..c0991720d76e 100644 --- a/packages/node/src/integrations/context.ts +++ b/packages/node/src/integrations/context.ts @@ -189,10 +189,20 @@ function getAppContext(): AppContext { return { app_start_time, app_memory }; } -function getDeviceContext(deviceOpt: DeviceContextOptions | true): DeviceContext { +/** + * Gets device information from os + */ +export function getDeviceContext(deviceOpt: DeviceContextOptions | true): DeviceContext { const device: DeviceContext = {}; - device.boot_time = new Date(Date.now() - os.uptime() * 1000).toISOString(); + // os.uptime or its return value seem to be undefined in certain environments (e.g. Azure functions). + // Hence, we only set boot time, if we get a valid uptime value. + // @see https://github.com/getsentry/sentry-javascript/issues/5856 + const uptime = os.uptime && os.uptime(); + if (typeof uptime === 'number') { + device.boot_time = new Date(Date.now() - uptime * 1000).toISOString(); + } + device.arch = os.arch(); if (deviceOpt === true || deviceOpt.memory) { diff --git a/packages/node/test/integrations/context.test.ts b/packages/node/test/integrations/context.test.ts new file mode 100644 index 000000000000..519e101187ff --- /dev/null +++ b/packages/node/test/integrations/context.test.ts @@ -0,0 +1,22 @@ +import * as os from 'os'; + +import { getDeviceContext } from '../../src/integrations/context'; + +describe('Context', () => { + describe('getDeviceContext', () => { + afterAll(() => { + jest.clearAllMocks(); + }); + + it('returns boot time if os.uptime is defined and returns a valid uptime', () => { + const deviceCtx = getDeviceContext({}); + expect(deviceCtx.boot_time).toEqual(expect.any(String)); + }); + + it('returns no boot time if os.uptime() returns undefined', () => { + jest.spyOn(os, 'uptime').mockReturnValue(undefined as unknown as number); + const deviceCtx = getDeviceContext({}); + expect(deviceCtx.boot_time).toBeUndefined(); + }); + }); +});