posva / mande

<700 bytes convenient and modern wrapper around fetch with smart extensible defaults
https://mande.esm.is
MIT License
1.2k stars 42 forks source link

Question: Anyway to get error message which is returned by server #307

Closed buenyaminyilmaz closed 1 year ago

buenyaminyilmaz commented 2 years ago

Hi there, i am trying to use mande. Is there any way to catch the error is given from server. For an example:

 try {
          const response = await registerApi.post({
            email: this.email,
            password: this.password,
            passwordConfirmed: this.passwordRepeat,
          })

          resolve(response)
        } catch (error) {
          console.log('ServerError', error)
          reject(error)
        }

registerApi is a mande instance. The server returns for me i this case 422 (Unprocessable Entity) and an error message. So how can i show this error message? console.log('ServerError', error) shows ServerError Error: Unprocessable Entity. Thank you in advance

wizbit commented 2 years ago

The error contains 2 extra items, response & data. I would handle the server error like this

 try {
   const response = await registerApi.post({
     email: this.email,
     password: this.password,
     passwordConfirmed: this.passwordRepeat,
   })
   resolve(response)
} catch (error) {
  console.log('ServerError', await error.response.json())
  reject(error)
}
alexey-us commented 2 years ago

Hello, I am also looking to catch the error from server

try {
    await this.api.post(deviceId + '/group/' + groupId + 's');
}
catch (error) {
   console.log(await error.response.json());
}

await error.response.json() - returned: Uncaught (in promise) TypeError: Failed to execute 'json' on 'Response': body stream already read

wizbit commented 2 years ago

error.data might contain the data you are after.

alexey-us commented 2 years ago

Thanks!

johannesronaldsson commented 2 years ago

Interesting... so I get nothing back, while the response gives JSON back. Not quite sure what's going on here... Love the library btw.

Screenshot 2022-04-12 at 16 14 21 Screenshot 2022-04-12 at 16 13 00 Screenshot 2022-04-12 at 16 13 07
koficoud commented 2 years ago

@johannesronaldsson You can access to the data using: error.body

try {
  const login = await api.post(apiUri, credentials);
} catch (error) {
  console.error(error.body)
}
bk973 commented 2 years ago

Was this issue resolved? @buenyaminyilmaz were the responses helpful

buenyaminyilmaz commented 2 years ago

Hi there, i will just test it out. i switched to axios, because i was in hurry

posva commented 1 year ago

I created https://github.com/posva/mande/issues/378 to track