-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
fix(nextjs): Delay error propagation until withSentry
is done
#4027
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
92341fe
rename variables
lobsterkatie 517f73e
pull cleanup work out into its own function
lobsterkatie 4702da7
stop awaiting result of domain-bound handler
lobsterkatie 68aa490
also flush before rethrowing error
lobsterkatie ec6822d
manually set error status on response
lobsterkatie 87efd29
fix wrapped handler type
lobsterkatie da218b3
add flushing tests
lobsterkatie ed6d624
rework comments in helper function to make it clear the loop ends
lobsterkatie 5c89c28
give the thrown error a more distinctive name
lobsterkatie 1af445e
Merge branch 'master' into kmclb-nextjs-fix-api-error-propagation
lobsterkatie File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,102 @@ | ||||||
import * as Sentry from '@sentry/node'; | ||||||
import * as utils from '@sentry/utils'; | ||||||
import { NextApiHandler, NextApiRequest, NextApiResponse } from 'next'; | ||||||
|
||||||
import { AugmentedNextApiResponse, withSentry, WrappedNextApiHandler } from '../../src/utils/withSentry'; | ||||||
|
||||||
const FLUSH_DURATION = 200; | ||||||
|
||||||
async function sleep(ms: number): Promise<void> { | ||||||
await new Promise(resolve => setTimeout(resolve, ms)); | ||||||
} | ||||||
/** | ||||||
* Helper to prevent tests from ending before `flush()` has finished its work. | ||||||
* | ||||||
* This is necessary because, like its real-life counterpart, our mocked `res.send()` below doesn't await `res.end() | ||||||
* (which becomes async when we wrap it in `withSentry` in order to give `flush()` time to run). In real life, the | ||||||
* request/response cycle is held open as subsequent steps wait for `end()` to emit its `prefinished` event. Here in | ||||||
* tests, without any of that other machinery, we have to hold it open ourselves. | ||||||
* | ||||||
* @param wrappedHandler | ||||||
* @param req | ||||||
* @param res | ||||||
*/ | ||||||
async function callWrappedHandler(wrappedHandler: WrappedNextApiHandler, req: NextApiRequest, res: NextApiResponse) { | ||||||
await wrappedHandler(req, res); | ||||||
|
||||||
// we know we need to wait at least this long for `flush()` to finish | ||||||
await sleep(FLUSH_DURATION); | ||||||
|
||||||
// should be <1 second, just long enough the `flush()` call to return, the original (pre-wrapping) `res.end()` to be | ||||||
// called, and the response to be marked as done | ||||||
while (!res.finished) { | ||||||
await sleep(100); | ||||||
} | ||||||
lobsterkatie marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
} | ||||||
|
||||||
// We mock `captureException` as a no-op because under normal circumstances it is an un-awaited effectively-async | ||||||
// function which might or might not finish before any given test ends, potentially leading jest to error out. | ||||||
const captureExceptionSpy = jest.spyOn(Sentry, 'captureException').mockImplementation(jest.fn()); | ||||||
lobsterkatie marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
const loggerSpy = jest.spyOn(utils.logger, 'log'); | ||||||
lobsterkatie marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
const flushSpy = jest.spyOn(Sentry, 'flush').mockImplementation(async () => { | ||||||
// simulate the time it takes time to flush all events | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
await sleep(FLUSH_DURATION); | ||||||
return true; | ||||||
}); | ||||||
lobsterkatie marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
||||||
describe('withSentry', () => { | ||||||
let req: NextApiRequest, res: NextApiResponse; | ||||||
|
||||||
const noShoesError = new Error('Oh, no! Charlie ate the flip-flops! :-('); | ||||||
|
||||||
const origHandlerNoError: NextApiHandler = async (_req, res) => { | ||||||
res.send('Good dog, Maisey!'); | ||||||
}; | ||||||
const origHandlerWithError: NextApiHandler = async (_req, _res) => { | ||||||
throw noShoesError; | ||||||
}; | ||||||
|
||||||
const wrappedHandlerNoError = withSentry(origHandlerNoError); | ||||||
const wrappedHandlerWithError = withSentry(origHandlerWithError); | ||||||
|
||||||
beforeEach(() => { | ||||||
req = { url: 'http://dogs.are.great' } as NextApiRequest; | ||||||
res = ({ | ||||||
send: function(this: AugmentedNextApiResponse) { | ||||||
this.end(); | ||||||
}, | ||||||
end: function(this: AugmentedNextApiResponse) { | ||||||
this.finished = true; | ||||||
}, | ||||||
} as unknown) as AugmentedNextApiResponse; | ||||||
}); | ||||||
|
||||||
afterEach(() => { | ||||||
jest.clearAllMocks(); | ||||||
}); | ||||||
|
||||||
describe('flushing', () => { | ||||||
it('flushes events before rethrowing error', async () => { | ||||||
lobsterkatie marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
try { | ||||||
await callWrappedHandler(wrappedHandlerWithError, req, res); | ||||||
} catch (err) { | ||||||
expect(err).toBe(noShoesError); | ||||||
} | ||||||
|
||||||
expect(captureExceptionSpy).toHaveBeenCalledWith(noShoesError); | ||||||
expect(flushSpy).toHaveBeenCalled(); | ||||||
expect(loggerSpy).toHaveBeenCalledWith('Done flushing events'); | ||||||
|
||||||
// This ensures the expect inside the `catch` block actually ran, i.e., that in the end the wrapped handler | ||||||
// errored out the same way it would without sentry, meaning the error was indeed rethrown | ||||||
expect.assertions(4); | ||||||
}); | ||||||
|
||||||
it('flushes events before finishing non-erroring response', async () => { | ||||||
lobsterkatie marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
await callWrappedHandler(wrappedHandlerNoError, req, res); | ||||||
|
||||||
expect(flushSpy).toHaveBeenCalled(); | ||||||
expect(loggerSpy).toHaveBeenCalledWith('Done flushing events'); | ||||||
}); | ||||||
}); | ||||||
}); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.