-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat(nestjs): Gracefully handle RPC scenarios in SentryGlobalFilter
#16066
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 1 commit
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
95f6c3c
add SentryRpcFilter
chargome e9d52ea
add jsdoc
chargome c197522
add rollup entrypoint
chargome cdf559d
revert microservice handling
chargome e4fd6f1
rm npm export
chargome 4c1cb11
remove peer
chargome 55ddeb9
Merge branch 'develop' into cg-nest-rpc-exceptions
chargome 3b5ca3f
remove dev dep
chargome 3e230bd
Merge branch 'develop' into cg-nest-rpc-exceptions
chargome 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,53 @@ | ||
import type { ArgumentsHost, HttpServer } from '@nestjs/common'; | ||
import { Catch, Logger } from '@nestjs/common'; | ||
import { RpcException } from '@nestjs/microservices'; | ||
import { captureException } from '@sentry/core'; | ||
import { SentryGlobalFilter } from './setup'; | ||
import { isExpectedError } from './helpers'; | ||
|
||
/** | ||
* Global filter to handle exceptions and report them to Sentry in nestjs microservice applications. | ||
* Extends the standard SentryGlobalFilter with RPC exception handling. | ||
*/ | ||
class SentryRpcFilter extends SentryGlobalFilter { | ||
chargome marked this conversation as resolved.
Show resolved
Hide resolved
|
||
private readonly _rpcLogger: Logger; | ||
|
||
public constructor(applicationRef?: HttpServer) { | ||
super(applicationRef); | ||
this._rpcLogger = new Logger('RpcExceptionsHandler'); | ||
} | ||
|
||
/** | ||
* Extend the base filter with RPC-specific handling. | ||
*/ | ||
public catch(exception: unknown, host: ArgumentsHost): void { | ||
const contextType = host.getType<string>(); | ||
|
||
if (contextType === 'rpc') { | ||
// Don't report RpcExceptions as they are expected errors | ||
if (exception instanceof RpcException) { | ||
throw exception; | ||
} | ||
|
||
if (!isExpectedError(exception)) { | ||
if (exception instanceof Error) { | ||
this._rpcLogger.error(exception.message, exception.stack); | ||
} | ||
captureException(exception); | ||
} | ||
|
||
// Wrap non-RpcExceptions in RpcExceptions to avoid misleading error messages | ||
if (!(exception instanceof RpcException)) { | ||
const errorMessage = exception instanceof Error ? exception.message : 'Internal server error'; | ||
throw new RpcException(errorMessage); | ||
} | ||
|
||
throw exception; | ||
} | ||
|
||
// For all other context types, use the base SentryGlobalFilter filter | ||
return super.catch(exception, host); | ||
} | ||
} | ||
Catch()(SentryRpcFilter); | ||
export { SentryRpcFilter }; |
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,128 @@ | ||
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest'; | ||
import type { ArgumentsHost } from '@nestjs/common'; | ||
import { RpcException } from '@nestjs/microservices'; | ||
import { SentryRpcFilter } from '../src/microservices'; | ||
import * as sentryCore from '@sentry/core'; | ||
|
||
vi.mock('@sentry/core', () => ({ | ||
captureException: vi.fn(), | ||
logger: { | ||
warn: vi.fn(), | ||
}, | ||
})); | ||
|
||
describe('SentryRpcFilter', () => { | ||
let filter: SentryRpcFilter; | ||
let mockHost: ArgumentsHost; | ||
|
||
beforeEach(() => { | ||
filter = new SentryRpcFilter(); | ||
|
||
mockHost = { | ||
getType: vi.fn().mockReturnValue('rpc'), | ||
switchToRpc: vi.fn().mockReturnValue({ | ||
getData: vi.fn(), | ||
getContext: vi.fn(), | ||
}), | ||
} as unknown as ArgumentsHost; | ||
|
||
vi.clearAllMocks(); | ||
}); | ||
|
||
afterEach(() => { | ||
vi.resetAllMocks(); | ||
}); | ||
|
||
it('should not report RpcException to Sentry', () => { | ||
const rpcException = new RpcException('Expected RPC error'); | ||
|
||
expect(() => { | ||
filter.catch(rpcException, mockHost); | ||
}).toThrow(RpcException); | ||
|
||
expect(sentryCore.captureException).not.toHaveBeenCalled(); | ||
}); | ||
|
||
it('should report regular Error to Sentry and wrap it in RpcException', () => { | ||
const error = new Error('Unexpected error'); | ||
|
||
expect(() => { | ||
filter.catch(error, mockHost); | ||
}).toThrow(RpcException); | ||
|
||
expect(sentryCore.captureException).toHaveBeenCalledWith(error); | ||
|
||
try { | ||
filter.catch(error, mockHost); | ||
} catch (e) { | ||
expect(e).toBeInstanceOf(RpcException); | ||
expect(e.message).toContain('Unexpected error'); | ||
} | ||
}); | ||
|
||
it('should wrap string exceptions in RpcException', () => { | ||
const errorMessage = 'String error message'; | ||
|
||
expect(() => { | ||
filter.catch(errorMessage, mockHost); | ||
}).toThrow(RpcException); | ||
|
||
expect(sentryCore.captureException).toHaveBeenCalledWith(errorMessage); | ||
}); | ||
|
||
it('should handle null/undefined exceptions', () => { | ||
expect(() => { | ||
filter.catch(null, mockHost); | ||
}).toThrow(RpcException); | ||
|
||
expect(sentryCore.captureException).toHaveBeenCalledWith(null); | ||
|
||
try { | ||
filter.catch(null, mockHost); | ||
} catch (e) { | ||
expect(e).toBeInstanceOf(RpcException); | ||
expect(e.message).toContain('Internal server error'); | ||
} | ||
}); | ||
|
||
it('should preserve the stack trace when possible', () => { | ||
const originalError = new Error('Original error'); | ||
originalError.stack = 'Original stack trace'; | ||
|
||
try { | ||
filter.catch(originalError, mockHost); | ||
} catch (e) { | ||
expect(e).toBeInstanceOf(RpcException); | ||
|
||
// Extract the error inside the RpcException | ||
const wrappedError = (e as any).getError(); | ||
|
||
// If implementation preserves stack, verify it | ||
if (typeof wrappedError === 'object' && wrappedError.stack) { | ||
expect(wrappedError.stack).toContain('Original stack trace'); | ||
} | ||
} | ||
}); | ||
|
||
it('should properly handle non-rpc context by delegating to parent', () => { | ||
// Mock HTTP context | ||
const httpHost = { | ||
getType: vi.fn().mockReturnValue('http'), | ||
switchToHttp: vi.fn().mockReturnValue({ | ||
getRequest: vi.fn(), | ||
getResponse: vi.fn(), | ||
}), | ||
} as unknown as ArgumentsHost; | ||
|
||
// Mock the parent class behavior | ||
const parentCatchSpy = vi.spyOn(filter, 'catch'); | ||
parentCatchSpy.mockImplementation(vi.fn()); | ||
|
||
const error = new Error('HTTP error'); | ||
|
||
filter.catch(error, httpHost); | ||
|
||
// Verify parent catch was called | ||
expect(parentCatchSpy).toHaveBeenCalled(); | ||
}); | ||
}); |
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
Oops, something went wrong.
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.