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.

Throwing errors in preprocess

See original GitHub issue

Hi there,

I’m trying to implement string coercion using z.preprocess, but there seems to be no way to indicate coercion errors:

export const Str = z.preprocess((value) => {
  switch (typeof value) {
    case 'bigint':
    case 'boolean':
    case 'number':
      return value.toString();

    case 'object':
      if (value == null) {
        return value;
      }
      if (value instanceof Date) {
        return value.toISOString();
      }
      throw new Error('Could not interpret value as string');

    case 'string':
      return value.trim();

    case 'undefined':
      return value;

    default:
      throw new Error('Could not interpret value as string');
  }
}, z.string());

Str.parse([]); // Error: Could not interpret value as string (rather than a ZodError)

I tried to create verbose workarounds but none ended up working. Thanks!

Kind regards, Hampus Kraft.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:12 (4 by maintainers)

github_iconTop GitHub Comments

23reactions
colinhackscommented, Oct 12, 2021

Perhaps you should be able to add issues inside preprocess similar to superRefine. I’ll look into this. It would save you from having to call coerceString twice.

2reactions
morgs32commented, Apr 6, 2022

Well @selimb this would not break from the idea that a transform would ONLY operate on valid data that has been “refined” before it. The feature here is that as you transform it into new data you can catch new errors that PREVENT transform. Put another way - the data might be INVALID in that it CANNOT be transformed correctly.

Let’s consider this note from the README on .transform():

⚠️ Transform functions must not throw. Make sure to use refinements before the transform to make sure the input can be parsed by the transform.

What if you are doing a transform that might not work? We shouldn’t have to look far for a transform that might NOT work.

For example, from the README on async-transforms:

const IdToUser = z
  .string()
  .uuid()
  .transform(async (id) => {
    return await getUserById(id);
  })

If you wrote this - hopefully your PR reviewer says, “what if getUserById doesn’t work?” Your answer cannot be, “well .transform must assume it operates on valid data”. So I guess we should update the README code snippet:

const IdToUser = z
  .string()
  .uuid()
  .transform(async (id) => {
    return await getUserById(id)
       .catch(e => {
          logger.log('Who would have guessed this person could not be found')
          // zod say you can't throw an error in a transform
          return null
       })
  })
  .refine(v => v, {
     message: 'See that transform above, must be that getUserById did not find our user',
  })

You know what else smells? You don’t have access to id in your message. Isn’t that a shame? Here’s a playground: https://runkit.com/morgs32/zod-transform

Thoughts?? @colinhacks whaddya think?

Read more comments on GitHub >

github_iconTop Results From Across the Web

How do I generate an error or warning in the C preprocessor?
The following code will throw an error at compile time if DEBUG is not defined: #ifndef DEBUG #error This is an error message...
Read more >
Diagnostics (The C Preprocessor)
The directive ' #warning ' is like ' #error ', but causes the preprocessor to issue a warning and continue preprocessing. The tokens...
Read more >
C Language: #error Directive - TechOnTheNet
Description. In the C Programming Language, the #error directive causes preprocessing to stop at the location where the directive is encountered.
Read more >
Preprocessor Error Messages
This error occurs when the address or value of a variable is incorrectly expressed because of faulty indirection.
Read more >
Loading Sklearn Preprocessing throws error - tools
While trying to import Sklearn an error is coming in Jupyter Notebook from sklearn import preprocessing or from sklearn.preprocessing import ...
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