question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Use default value on error

See original GitHub issue

I’d like to validate a value, and if that validation fails I don’t care about the error - I want to use a default value.

const strZ = z.string().default('hello world');
strZ.parse() // 'hello world'
strZ.parse('hi') // 'hi'
strZ.parse(23) // error, but I want 'hello world'

I can’t figure out a clean way to do this without writing my own wrapper around zod. Is this supported already by the library?

Issue Analytics

  • State:open
  • Created a year ago
  • Reactions:1
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
altitudemscommented, Sep 29, 2022

Looks like this might be a good workaround:

const withFallback = <T>(schema: z.ZodType<T>, fallback: T) =>
  z.preprocess(
    (value) => {
      const parseResult = schema.safeParse(value);
      if (parseResult.success) return value;
      return fallback;
    },
    z.custom((v) => true)
  );

Example Usage

3reactions
0916dhkimcommented, Sep 28, 2022

Throwing in some ideas here:

type Parser<T> = (val: unknown) => T;
const customSchema = <T>(parser: Parser<T>) => z.unknown().transform(parser);

// Now you can define your own zod schema like this:
const catOrDogSchema = customSchema((val) => {
  if (val === "cat" || val === "dog") return val;
  throw new Error("Not cat or dog");
});
catOrDogSchema.parse("cat") // type: "cat" | "dog"

We can extend this and make withFallback helper:

const withFallback = <T>(schema: z.ZodType<T>, fallback: T) =>
  customSchema((val) => {
    const parsed = schema.safeParse(val);
    if (parsed.success) return parsed.data;
    return fallback;
  });

@matthewoates

const strZ = withFallback(z.string().default("hello world"), "fallback");
strZ.parse() // "hello world"
strZ.parse("hi") // "hi"
strZ.parse(23) // "fallback"

@zavarka

const urlQueryParams = z.object({
  // ...
  queryParam7: withFallback(
    z.string().nullish().refine(isUUID),
    null
  ),
});
urlQueryParams.parse({
  // ...
  queryParam7: 13 // INVALID
}); // but it parses successfully. { queryParam7: null }

This works, but it would be nice if zod provided corresponding methods like z.custom() and z.string().fallback().

Read more comments on GitHub >

github_iconTop Results From Across the Web

how to set default value in case of error - Stack Overflow
I'd recommend to go by creating a utility function as below. export const getSafe = (fn, defaultValue=null) => { try { ...
Read more >
Set Default Value Error On SQL SERVER - Microsoft Q&A
Set Default Value Error On SQL SERVER. I Cannot Set Default Value For the existing columns, even though there are no constraint or...
Read more >
3 Ways to Set Default Value in JavaScript | SamanthaMing.com
Let's break down the 3 different ways to set Default Values using logical operator, ternary, and if/else...
Read more >
How to set default values in Code Steps and avoid errors for ...
As you can see, value3 came through with a default value that we set instead of causing the Step to error. With Javascript,...
Read more >
Default parameters - JavaScript - MDN Web Docs
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found