Skip to content

Commit

Permalink
chore: add fromZodError runtime check to throw TypeError on bad usage (
Browse files Browse the repository at this point in the history
…#296)

* chore: handles and throws TypeError on fromZodError invalid use

* chore: add changeset

* chore: better TypeError message
  • Loading branch information
thanoskrg authored Apr 23, 2024
1 parent 6b4e8a0 commit 35a28c6
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/itchy-elephants-judge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'zod-validation-error': minor
---

Add runtime check in `fromZodError` and throw dev-friendly `TypeError` suggesting usage of `fromError` instead
15 changes: 15 additions & 0 deletions lib/fromZodError.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -454,4 +454,19 @@ describe('fromZodError()', () => {
}
}
});

test('throws a dev-friendly TypeError on invalid input', () => {
const input = new Error("I wish I was a ZodError, but I'm not");

try {
// @ts-expect-error
fromZodError(input);
} catch (err) {
expect(err).toBeInstanceOf(TypeError);
// @ts-expect-error
expect(err.message).toMatchInlineSnapshot(
`"Invalid zodError param; expected instance of ZodError. Did you mean to use the "fromError" method instead?"`
);
}
});
});
9 changes: 8 additions & 1 deletion lib/fromZodError.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as zod from 'zod';
import {
ISSUE_SEPARATOR,
MAX_ISSUES_IN_MESSAGE,
Expand All @@ -8,8 +9,8 @@ import {
import { getMessageFromZodIssue } from './fromZodIssue.ts';
import { prefixMessage } from './prefixMessage.ts';
import { ValidationError } from './ValidationError.ts';
import { fromError } from './fromError.ts';
import type { FromZodIssueOptions } from './fromZodIssue.ts';
import type * as zod from 'zod';

export type ZodError = zod.ZodError;

Expand All @@ -21,6 +22,12 @@ export function fromZodError(
zodError: ZodError,
options: FromZodErrorOptions = {}
): ValidationError {
if (!(zodError instanceof zod.ZodError)) {
throw new TypeError(
`Invalid zodError param; expected instance of ZodError. Did you mean to use the "${fromError.name}" method instead?`
);
}

const {
maxIssuesInMessage = MAX_ISSUES_IN_MESSAGE,
issueSeparator = ISSUE_SEPARATOR,
Expand Down

0 comments on commit 35a28c6

Please sign in to comment.