diff --git a/src/index.ts b/src/index.ts index 9b8fa3bdd..a25a102b5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -206,5 +206,6 @@ export * from './util/RecordObject'; export * from './util/SequenceHandler'; export * from './util/StreamUtil'; export * from './util/TermUtil'; +export * from './util/UnsupportedAsyncHandler'; export * from './util/Vocabularies'; export * from './util/WaterfallHandler'; diff --git a/src/util/UnsupportedAsyncHandler.ts b/src/util/UnsupportedAsyncHandler.ts new file mode 100644 index 000000000..936d433e2 --- /dev/null +++ b/src/util/UnsupportedAsyncHandler.ts @@ -0,0 +1,22 @@ +import { AsyncHandler } from './AsyncHandler'; +import { NotImplementedHttpError } from './errors/NotImplementedHttpError'; + +/** + * Handler that does not support any input and will always throw an error. + */ +export class UnsupportedAsyncHandler extends AsyncHandler { + private readonly errorMessage?: string; + + public constructor(errorMessage?: string) { + super(); + this.errorMessage = errorMessage; + } + + public async canHandle(): Promise { + throw new NotImplementedHttpError(this.errorMessage); + } + + public async handle(): Promise { + return this.canHandle(); + } +} diff --git a/test/unit/util/UnsupportedAsyncHandler.test.ts b/test/unit/util/UnsupportedAsyncHandler.test.ts new file mode 100644 index 000000000..7866b9c0e --- /dev/null +++ b/test/unit/util/UnsupportedAsyncHandler.test.ts @@ -0,0 +1,18 @@ +import { NotImplementedHttpError } from '../../../src/util/errors/NotImplementedHttpError'; +import { UnsupportedAsyncHandler } from '../../../src/util/UnsupportedAsyncHandler'; + +describe('An UnsupportedAsyncHandler', (): void => { + it('throws a default error when no message is set.', async(): Promise => { + const handler = new UnsupportedAsyncHandler(); + await expect(handler.canHandle()).rejects.toThrow(NotImplementedHttpError); + await expect(handler.handle()).rejects.toThrow(NotImplementedHttpError); + await expect(handler.handleSafe(null)).rejects.toThrow(NotImplementedHttpError); + }); + + it('throws the specified error when a message is set.', async(): Promise => { + const handler = new UnsupportedAsyncHandler('custom error'); + await expect(handler.canHandle()).rejects.toThrow('custom error'); + await expect(handler.handle()).rejects.toThrow('custom error'); + await expect(handler.handleSafe(null)).rejects.toThrow('custom error'); + }); +});