Daniel Tonon
Daniel Tonon

Reputation: 10412

How do I fetch-mock an accurate server error?

The issue:

fetchmock

fetchMock.get('glob:https://*/server-api-uri', () => {
  throw { example: 'error' }
})

Source JS file:

exampleServerCall().catch(error => {
  console.log(error) // error = "[ object object ]" :(
})

So my catch statements are returning with a useless "[ object object ]" string when what I really want is access to the full mocked server error.

Upvotes: 3

Views: 2595

Answers (1)

Daniel Tonon
Daniel Tonon

Reputation: 10412

After reading the MDN docs for throw, I found documentation for how to throw a custom object in a throw handler.

You need to do it by creating a custom class object.

fetchmock

class CustomError {
    example = 'error'
}

fetchMock.get('glob:https://*/server-api-uri', () => {
  throw new CustomError()
})

source JS file:

exampleServerCall().catch(error => {
  console.log(error) // error = { example: 'error' } :D
})

Upvotes: 1

Related Questions