Got: Incorrect url causes `.json is not a function` error

Created on 17 Jan 2020  Â·  2Comments  Â·  Source: sindresorhus/got

Describe the bug

  • Node.js version: 12.4.0
  • OS & version: Arch Linux Linux 5.4.11-arch1-1

When a url given to the got.post / got.get functions is incorrect AND the function is followed with a .json(), this error is thrown:

    TypeError: got.post(...).json is not a function

Actual behavior

Error is thrown (see above)

Expected behavior

Throw HTTP Error 404, Not found

Code to reproduce

function test(){
  return got.get('undefined/https://jsonplaceholder.typicode.com/todos/1').json();
};

test();

Checklist

  • [x] I have read the documentation.
  • [x] I have tried my code with the latest version of Node.js and Got.
bug ✭ help wanted ✭

All 2 comments

Looks like when got attempts to normalize arguments it catches any thrown exceptions and can in some cases return a rejected Promise. Obviously this is a normal promise so it does not include any of the convenience methods that would usually be included (like json).

A possibly naive solution might be to just move the argument normalization outside of the try/catch. A better solution might be to make a decorator that can augment the rejected promise to include the convenience methods so that they also return a rejected promise.

I'd be happy to take this on, but I could use a little direction from a maintainer since I'm kind of new to this codebase.

In the as-promise.ts file export a function that would shim rejecting promises: let's call it createRejection:

const createRejection = (error: Error) => {
    const promise = Promise.reject(error) as asPromise;
    const returnPromise = () => promise;

    promise.json = returnPromise;
    promise.text = returnPromise;
    promise.buffer = returnPromise;
    promise.on = returnPromise;

    return promise;
};
Was this page helpful?
0 / 5 - 0 ratings