Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Throw syntax errors when parsing invalid input #43

Merged
merged 5 commits into from
Nov 1, 2022

Conversation

haines
Copy link
Contributor

@haines haines commented Oct 26, 2022

At the moment, if parse encounters valid JSON in an unexpected format, it may either throw a confusing error, or silently return the wrong output.

parse('"hello"') // => 'h'
parse('42') // =>  ReferenceError: Cannot access 'hydrated' before initialization
parse('true') // => undefined
parse('null') // => TypeError: Cannot read properties of null (reading 'length')
parse('{}') // => undefined
parse('[]') // => undefined

This PR introduces checks for unexpected values before hydrating and throws a SyntaxError if the input cannot be parsed.

@Rich-Harris
Copy link
Owner

Thank you! Since devalue.parse needs to be as small as possible (as it's designed to be used in the browser to hydrate server payloads), I made a few tweaks. The expectation is that you'd always be using it with the output of devalue.stringify, so if the input is incorrect, the specific way in which it's incorrect doesn't really matter — it just means that things haven't been wired up correctly. As such, I think a generic Invalid input error is sufficient, given that it results in a smaller library than the more descriptive errors.

@Rich-Harris Rich-Harris merged commit e928a52 into Rich-Harris:master Nov 1, 2022
@haines haines deleted the syntax-errors branch November 1, 2022 21:36
@haines
Copy link
Contributor Author

haines commented Nov 1, 2022

Sounds good, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants