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

fix: explain why json() cannot be used in form actions #12829

Merged
merged 7 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/healthy-planets-dance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

fix: better error message when a `Result` is returned from a form action
8 changes: 8 additions & 0 deletions packages/kit/src/runtime/server/page/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,14 @@ function try_deserialize(data, fn, route_id) {
// If we're here, the data could not be serialized with devalue
const error = /** @type {any} */ (e);

// if someone tries to use `json()` in their action
if (data instanceof Response) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there's nothing really specific in this error message about a Response, so I'm wondering why the if below doesn't catch it. It seems like we could combine the two. Maybe they need to check if it's an instance of DevalueError or if name is DevalueError?

Copy link
Member Author

@eltigerchino eltigerchino Oct 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It still catches it but the error message is usually "Cannot stringify arbitrary non-POJOs" which can be unhelpful. We could combine the two but I'm wondering if there are instances where devalue's error message is preferred.

throw new Error(
`Data returned from action inside ${route_id} is not serializable. Form actions need to return plain objects or fail(). E.g. return { success: true } or return fail(400, { message: "invalid" });`
);
}

// if devalue could not serialize a property on the object, etc.
if ('path' in error) {
eltigerchino marked this conversation as resolved.
Show resolved Hide resolved
let message = `Data returned from action inside ${route_id} is not serializable: ${error.message}`;
if (error.path !== '') message += ` (data.${error.path})`;
Expand Down
Loading