sindresorhus / got

🌐 Human-friendly and powerful HTTP request library for Node.js
MIT License
14.2k stars 934 forks source link

How do you go about reading non-2xx/3xx response bodies? #2024

Closed RavenHursT closed 2 years ago

RavenHursT commented 2 years ago

What would you like to discuss?

I ran into a problem while using a library that's using got for making server-side requests:

https://github.com/MONEI/Shopify-api-node/issues/534

It appears that got, if it receives a response w/ a non-2xx/3xx status code, that it just packages up a custom HTTPError object and throws it.

The problem w/ that approach is that it doesn't seem like there's any way to get ahold of the response's body bytes (assuming there are any). It seems like all that's thrown are essentially the code and the message. Any catch block will not have any way to access the body of the response.

In my case, the APIs being called, when errors are sent via 4xx responses, the body of those responses comes w/ very important data to help in debugging usage of the APIs in question.

Am I missing something? Is there some other way to get ahold of the body so that the stream can be read and parsed? ...

Checklist

RavenHursT commented 2 years ago

Looks like there's a beforeError hook.. https://github.com/sindresorhus/got/blob/4f24bd11fb50757ec8753a74e4a7b18de95ba155/source/core/index.ts#L1179-L1182

... but even then, you still only have access to error, which it looks like is just the HttpError in the aforementioned OP.

Maybe do a .bind(this) on the hook method somewhere so the consumer of this could at least reference this._request, or better yet, just change 1181 to something like this, so the user can have some kind of introspection on the request and response in question...

error = await hook(error, this._response)

RavenHursT commented 2 years ago

Oh wait.. just saw this comment in the source.. https://github.com/sindresorhus/got/blob/4f24bd11fb50757ec8753a74e4a7b18de95ba155/source/core/errors.ts#L87-L93

Maybe it does have a response object?

Oddly enough, it doesn't show p in the console when I log out the HTTPError object in my catch block:

Screen Shot 2022-04-11 at 6 47 32 PM
RavenHursT commented 2 years ago

Ok.. so the Response object is indeed there. Wish it had been more apparent that this was the case besides a comment buried in the source code.

Closing.

RavenHursT commented 2 years ago

Apparently it is possible to get ahold of the response in question.. just had to dig through got's source code to find a comment buried there. Closing.

https://github.com/sindresorhus/got/issues/2024#issuecomment-1095862934

szmarczak commented 2 years ago

https://github.com/sindresorhus/got/blob/main/documentation/8-errors.md#errors