elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.83k stars 98 forks source link

How to get error json response? #171

Closed SharkFourSix closed 1 year ago

SharkFourSix commented 1 year ago

According to this https://github.com/elbywan/wretch#catchers- , I should be able to get a response JSON object even during errors. However, the error parameter does not have a .json property. The .text property is present but having to serialize to JSON manually is very counterintuitive.

wretch("...")
  .get()
  .badRequest((err) => console.log(err.json[0].Message))
  .res();
type WretchError = Error & {
  status: number;
  response: WretchResponse;
  text?: string;
  json?: Object;
};

Perhaps there is another way that I'm not aware of?

elbywan commented 1 year ago

Hey @SharkFourSix,

However, the error parameter does not have a .json property. The .text property is present but having to serialize to JSON manually is very counterintuitive

You can call the .errorType method to specify the error body type. Putting .errorType("json") in the chain should populate the error.json field.

SharkFourSix commented 1 year ago

Thanks. :+1: That worked. I was about to switch to axios because of that that little inconvenience which can build up into lots of boilerplate code :sweat_smile:

SharkFourSix commented 1 year ago

Bump...

So it appears that this applies to all the error "catchers"? Is there a way to only call the parsing on demand in the handlers?

Because as it appears I have to design my API to always return a JSON response, again, something which is counterintuitive :/

I'm getting a JSON conversion error because some responses are only returning standard HTTP responses without any additional JSON data.

Can't you only parse JSON by looking at the content-type response?

elbywan commented 1 year ago

Because as it appears I have to design my API to always return a JSON response, again, something which is counterintuitive :/

Absolutely, I fully agree 👍.

Can't you only parse JSON by looking at the content-type response?

No, but this is an excellent idea! I just released v2.5.0 which will automatically deserialize the error body if the response content-type header is set to application/json, which should make it unnecessary to set .errorType in the first place if your server sets the header properly.

The error.text property will still get populated in case the parsing fails.

SharkFourSix commented 1 year ago

Cool. That was quick too. :+1: