10

When using SvelteKit and there are issues on endpoints and form action handlers (+page.server.ts and +server.ts), when should throw error and when should return fail be used? For fail:

return fail( status , {details} )

and when should an error be thrown instead?

throw error( status ,  message )

If the form action handler and endpoint are called from a use:enhancement form does that change which is more suitable to use? Will both be sent to the use:enhancement form handler or does error bypass it and go directly to +error.svelte? In the docs I do not see how the fail is handled specifically in comparison to the thrown error?

CC BY-SA 4.0

1 Answer 1

11

error is for serious issues that cause the +error.svelte to be displayed.

fail is for form action results that are invalid, which can return relevant data to show, e.g. validation errors for form fields.

If the request couldn't be processed because of invalid data, you can return validation errors — along with the previously submitted form values — back to the user so that they can try again. The fail function lets you return an HTTP status code (typically 400 or 422, in the case of validation errors) along with the data. The status code is available through $page.status and the data through form

CC BY-SA 4.0
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.