From 8a73ebf9de9fd97e5be3966807e475459441055e Mon Sep 17 00:00:00 2001 From: Igor Savin Date: Mon, 22 Jan 2024 17:39:36 +0200 Subject: [PATCH] Add typeguard for ResponseStatusError --- index.ts | 1 + src/errors/ResponseStatusError.ts | 1 + src/errors/errorTypeGuards.spec.ts | 25 +++++++++++++++++++++++++ src/errors/errorTypeGuards.ts | 5 +++++ 4 files changed, 32 insertions(+) create mode 100644 src/errors/errorTypeGuards.spec.ts create mode 100644 src/errors/errorTypeGuards.ts diff --git a/index.ts b/index.ts index 838a89c..e8ec7bc 100644 --- a/index.ts +++ b/index.ts @@ -25,6 +25,7 @@ export { type InternalErrorParams, } from './src/errors/InternalError' export { ResponseStatusError } from './src/errors/ResponseStatusError' +export { isResponseStatusError } from './src/errors/errorTypeGuards' export { ConfigScope } from './src/config/ConfigScope' export { ensureClosingSlashTransformer } from './src/config/configTransformers' diff --git a/src/errors/ResponseStatusError.ts b/src/errors/ResponseStatusError.ts index 2fd4dca..bf185a6 100644 --- a/src/errors/ResponseStatusError.ts +++ b/src/errors/ResponseStatusError.ts @@ -5,6 +5,7 @@ import { InternalError } from './InternalError' export class ResponseStatusError extends InternalError { // eslint-disable-next-line @typescript-eslint/no-explicit-any public readonly response: RequestResult + public readonly isResponseStatusError = true // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(requestResult: RequestResult, requestLabel = 'N/A') { diff --git a/src/errors/errorTypeGuards.spec.ts b/src/errors/errorTypeGuards.spec.ts new file mode 100644 index 0000000..c017d52 --- /dev/null +++ b/src/errors/errorTypeGuards.spec.ts @@ -0,0 +1,25 @@ +import { describe } from 'vitest' + +import { InternalError } from './InternalError' +import { ResponseStatusError } from './ResponseStatusError' +import { isResponseStatusError } from './errorTypeGuards' + +describe('errorTypeGuards', () => { + describe('isResponseStatusError', () => { + it('Returns true for ResponseStatusError', () => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument,@typescript-eslint/no-explicit-any + const error = new ResponseStatusError({} as any, 'label') + + expect(isResponseStatusError(error)).toBe(true) + }) + + it('Returns false for not a ResponseStatusError', () => { + const error = new InternalError({ + message: 'message', + errorCode: 'CODE', + }) + + expect(isResponseStatusError(error)).toBe(false) + }) + }) +}) diff --git a/src/errors/errorTypeGuards.ts b/src/errors/errorTypeGuards.ts new file mode 100644 index 0000000..d6bd0fa --- /dev/null +++ b/src/errors/errorTypeGuards.ts @@ -0,0 +1,5 @@ +import type { ResponseStatusError } from './ResponseStatusError' + +export function isResponseStatusError(entity: unknown): entity is ResponseStatusError { + return 'isResponseStatusError' in (entity as ResponseStatusError) +}