-
Notifications
You must be signed in to change notification settings - Fork 171
feat(event-handler): add event handler registry #4307
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
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,74 @@ | ||
import type { GenericLogger } from '@aws-lambda-powertools/commons/types'; | ||
import type { | ||
ErrorConstructor, | ||
ErrorHandler, | ||
ErrorHandlerRegistryOptions, | ||
} from '../types/rest.js'; | ||
|
||
export class ErrorHandlerRegistry { | ||
readonly #handlers: Map<ErrorConstructor, ErrorHandler> = new Map(); | ||
|
||
readonly #logger: Pick<GenericLogger, 'debug' | 'warn' | 'error'>; | ||
|
||
public constructor(options: ErrorHandlerRegistryOptions) { | ||
this.#logger = options.logger; | ||
} | ||
|
||
/** | ||
* Registers an error handler for one or more error types. | ||
* | ||
* The handler will be called when an error of the specified type(s) is thrown. | ||
* If multiple error types are provided, the same handler will be registered | ||
* for all of them. | ||
* | ||
* @param errorType - The error constructor(s) to register the handler for | ||
* @param handler - The error handler function to call when the error occurs | ||
*/ | ||
public register<T extends Error>( | ||
errorType: ErrorConstructor<T> | ErrorConstructor<T>[], | ||
handler: ErrorHandler<T> | ||
): void { | ||
const errorTypes = Array.isArray(errorType) ? errorType : [errorType]; | ||
|
||
for (const type of errorTypes) { | ||
if (this.#handlers.has(type)) { | ||
this.#logger.warn( | ||
`Handler for ${type.name} already exists. The previous handler will be replaced.` | ||
); | ||
} | ||
this.#handlers.set(type, handler as ErrorHandler); | ||
} | ||
} | ||
|
||
/** | ||
* Resolves an error handler for the given error instance. | ||
* | ||
* The resolution process follows this order: | ||
* 1. Exact constructor match | ||
* 2. instanceof checks for inheritance | ||
* 3. Name-based matching (fallback for bundling issues) | ||
* | ||
* @param error - The error instance to find a handler for | ||
* @returns The error handler function or null if no match found | ||
*/ | ||
public resolve(error: Error): ErrorHandler | null { | ||
const exactHandler = this.#handlers.get( | ||
error.constructor as ErrorConstructor | ||
); | ||
if (exactHandler != null) return exactHandler; | ||
|
||
for (const [errorType, handler] of this.#handlers) { | ||
if (error instanceof errorType) { | ||
return handler; | ||
} | ||
} | ||
|
||
for (const [errorType, handler] of this.#handlers) { | ||
if (error.name === errorType.name) { | ||
return handler; | ||
} | ||
} | ||
|
||
return null; | ||
} | ||
} |
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
166 changes: 166 additions & 0 deletions
166
packages/event-handler/tests/unit/rest/ErrorHandlerRegistry.test.ts
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,166 @@ | ||
import { describe, expect, it } from 'vitest'; | ||
import { HttpErrorCodes } from '../../../src/rest/constants.js'; | ||
import { ErrorHandlerRegistry } from '../../../src/rest/ErrorHandlerRegistry.js'; | ||
import type { HttpStatusCode } from '../../../src/types/rest.js'; | ||
|
||
const createErrorHandler = | ||
(statusCode: HttpStatusCode, message?: string) => (error: Error) => ({ | ||
statusCode, | ||
error: error.name, | ||
message: message ?? error.message, | ||
}); | ||
|
||
class CustomError extends Error { | ||
constructor(message: string) { | ||
super(message); | ||
this.name = 'CustomError'; | ||
} | ||
} | ||
|
||
class AnotherError extends Error { | ||
constructor(message: string) { | ||
super(message); | ||
this.name = 'AnotherError'; | ||
} | ||
} | ||
|
||
class InheritedError extends CustomError { | ||
constructor(message: string) { | ||
super(message); | ||
this.name = 'InheritedError'; | ||
} | ||
} | ||
|
||
describe('Class: ErrorHandlerRegistry', () => { | ||
it('logs a warning when registering a duplicate error handler', () => { | ||
// Prepare | ||
const registry = new ErrorHandlerRegistry({ logger: console }); | ||
const handler1 = createErrorHandler(HttpErrorCodes.BAD_REQUEST, 'first'); | ||
const handler2 = createErrorHandler(HttpErrorCodes.NOT_FOUND, 'second'); | ||
|
||
// Act | ||
registry.register(CustomError, handler1); | ||
registry.register(CustomError, handler2); | ||
|
||
// Assess | ||
expect(console.warn).toHaveBeenCalledWith( | ||
'Handler for CustomError already exists. The previous handler will be replaced.' | ||
); | ||
|
||
const result = registry.resolve(new CustomError('test')); | ||
expect(result).toBe(handler2); | ||
}); | ||
|
||
it('registers handlers for multiple error types', () => { | ||
// Prepare | ||
const registry = new ErrorHandlerRegistry({ logger: console }); | ||
const handler = createErrorHandler(HttpErrorCodes.BAD_REQUEST); | ||
|
||
// Act | ||
registry.register([CustomError, AnotherError], handler); | ||
|
||
// Assess | ||
expect(registry.resolve(new CustomError('test'))).toBe(handler); | ||
expect(registry.resolve(new AnotherError('test'))).toBe(handler); | ||
}); | ||
|
||
it('resolves handlers using exact constructor match', () => { | ||
// Prepare | ||
const registry = new ErrorHandlerRegistry({ logger: console }); | ||
const customHandler = createErrorHandler(HttpErrorCodes.BAD_REQUEST); | ||
const anotherHandler = createErrorHandler( | ||
HttpErrorCodes.INTERNAL_SERVER_ERROR | ||
); | ||
|
||
// Act | ||
registry.register(CustomError, customHandler); | ||
registry.register(AnotherError, anotherHandler); | ||
|
||
// Assess | ||
expect(registry.resolve(new CustomError('test'))).toBe(customHandler); | ||
expect(registry.resolve(new AnotherError('test'))).toBe(anotherHandler); | ||
}); | ||
|
||
it('resolves handlers using instanceof for inheritance', () => { | ||
// Prepare | ||
const registry = new ErrorHandlerRegistry({ logger: console }); | ||
const baseHandler = createErrorHandler(HttpErrorCodes.BAD_REQUEST); | ||
|
||
// Act | ||
registry.register(CustomError, baseHandler); | ||
|
||
// Assess | ||
const inheritedError = new InheritedError('test'); | ||
expect(registry.resolve(inheritedError)).toBe(baseHandler); | ||
}); | ||
|
||
it('resolves handlers using name-based matching', () => { | ||
// Prepare | ||
const registry = new ErrorHandlerRegistry({ logger: console }); | ||
const handler = createErrorHandler(HttpErrorCodes.BAD_REQUEST); | ||
|
||
// Act | ||
registry.register(CustomError, handler); | ||
|
||
const errorWithSameName = new Error('test'); | ||
errorWithSameName.name = 'CustomError'; | ||
|
||
// Assess | ||
expect(registry.resolve(errorWithSameName)).toBe(handler); | ||
}); | ||
|
||
it('returns null when no handler is found', () => { | ||
// Prepare | ||
const registry = new ErrorHandlerRegistry({ logger: console }); | ||
const handler = createErrorHandler(HttpErrorCodes.BAD_REQUEST); | ||
|
||
// Act | ||
registry.register(CustomError, handler); | ||
|
||
// Assess | ||
expect(registry.resolve(new AnotherError('test'))).toBeNull(); | ||
expect(registry.resolve(new Error('test'))).toBeNull(); | ||
}); | ||
|
||
it('prioritizes exact constructor match over instanceof', () => { | ||
// Prepare | ||
const registry = new ErrorHandlerRegistry({ logger: console }); | ||
const baseHandler = createErrorHandler(HttpErrorCodes.BAD_REQUEST); | ||
const specificHandler = createErrorHandler( | ||
HttpErrorCodes.INTERNAL_SERVER_ERROR | ||
); | ||
|
||
// Act | ||
registry.register(CustomError, baseHandler); | ||
registry.register(InheritedError, specificHandler); | ||
|
||
// Assess | ||
expect(registry.resolve(new InheritedError('test'))).toBe(specificHandler); | ||
}); | ||
|
||
it('prioritizes instanceof match over name-based matching', () => { | ||
// Prepare | ||
const registry = new ErrorHandlerRegistry({ logger: console }); | ||
const baseHandler = createErrorHandler(HttpErrorCodes.BAD_REQUEST); | ||
const nameHandler = createErrorHandler( | ||
HttpErrorCodes.INTERNAL_SERVER_ERROR | ||
); | ||
|
||
// Create a class with different name but register with name matching | ||
class DifferentNameError extends Error { | ||
constructor(message: string) { | ||
super(message); | ||
this.name = 'CustomError'; // Same name as CustomError | ||
} | ||
} | ||
|
||
// Act | ||
registry.register(CustomError, baseHandler); | ||
registry.register(DifferentNameError, nameHandler); | ||
|
||
const error = new DifferentNameError('test'); | ||
|
||
// Assess | ||
expect(registry.resolve(error)).toBe(nameHandler); | ||
}); | ||
}); |
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.