SolidJSS
SolidJS3y ago
18 replies
Grahf

Felte Form server error handling

Hello. I'm having trouble displaying errors from the server with a Felte form. According to the docs "You can add an onError function to the createForm configuration that will be called if the onSubmit function throws an error." I've added the onError function but I'm not getting the errors from the onSubmit function.

My form looks like this:
  const { form, errors } = createForm({
    onSubmit: async (values, { event }) => {
      try {
        const formData = new FormData(event.target)

        const response = await fetch('/api/login', {
          method: 'POST',
          body: formData,
        })

        const data = await response.json()
        return data
      } catch (error) {
        console.warn('Fetch call failed')
        console.error(error)
        // You might want to handle the error or return some indication of failure
        throw error
      }
    },
    onSuccess(response, context) {
      // Do something with the returned value from `onSubmit`.
    },
    onError(err, context) {
      // Do something with the error thrown from `onSubmit`.
      console.log('test err: ', err)
    },
  })


And the error handling part of my server looks like this:
 const errors = { username: '', password: '' }

  if (typeof name !== 'string' || name.length < 3) {
    errors.username += 'Please enter a three character or longer username.'
  }
  if (typeof password !== 'string' || password.length < 5) {
    errors.password += 'Password must be at least five characters.'
  }

  const hasErrors = Object.values(errors).some((msg) => msg)

  if (hasErrors) {
    console.debug(errors)

    return new Response(
      JSON.stringify({
        message: 'Login Failed',
        errors: errors,
      }),
      {
        status: 400,
      },
    )
  }

I get the 400 status code back (see screenshot). But no console.log from the onError function
image.png
Was this page helpful?