got#HTTPError TypeScript Examples

The following examples show how to use got#HTTPError. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: errors.ts    From blockfrost-js with Apache License 2.0 6 votes vote down vote up
handleError = (
  error: GotError,
): BlockfrostServerError | BlockfrostClientError => {
  if (error instanceof HTTPError) {
    const responseBody = error.response.body;

    if (isBlockfrostErrorResponse(responseBody)) {
      return new BlockfrostServerError(responseBody);
    } else {
      // response.body may contain html output (eg. errors returned by nginx)
      const { statusCode } = error.response;
      const statusText = error.response.statusMessage ?? error.message;
      return new BlockfrostServerError({
        status_code: statusCode,
        message: `${statusCode}: ${statusText}`,
        error: statusText,
      });
    }
  }

  // system errors such as -3008 ENOTFOUND and various got errors like ReadError, CacheError, MaxRedirectsError, TimeoutError,...
  // https://github.com/sindresorhus/got/blob/main/documentation/8-errors.md
  return new BlockfrostClientError({
    code: error.code ?? 'ERR_GOT_REQUEST_ERROR', // ENOTFOUND, ETIMEDOUT...
    message: error.message, // getaddrinfo ENOTFOUND cardano-testnet.blockfrost.io'
  });
}
Example #2
Source File: api.ts    From eufy-security-client with MIT License 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    public async request(request: HTTPApiRequest): Promise<ApiResponse> {
        this.log.debug("Request:", { method: request.method, endpoint: request.endpoint, token: this.token, data: request.data });
        try {
            const internalResponse = await this.requestEufyCloud(request.endpoint, {
                method: request.method,
                json: request.data,
            });
            const response: ApiResponse = {
                status: internalResponse.statusCode,
                statusText: internalResponse.statusMessage ? internalResponse.statusMessage : "",
                headers: internalResponse.headers,
                data: internalResponse.body,
            };
            this.log.debug("Response:", { response: response.data });

            return response;
        } catch (error) {
            if (error instanceof HTTPError) {
                if (error.response.statusCode === 401) {
                    this.invalidateToken();
                    this.log.error("Status return code 401, invalidate token", { status: error.response.statusCode, statusText: error.response.statusMessage });
                    this.emit("close");
                    this.connected = false;
                }
            }
            throw error;
        }
    }
Example #3
Source File: index.test.ts    From ens-metadata-service with MIT License 6 votes vote down vote up
test('get /:contractAddress/:tokenId for unknown namehash', async (t: ExecutionContext<TestContext>) => {
  const {
    response: { statusCode, body },
  }: HTTPError = await t.throwsAsync(
    () => got(`rinkeby/${NAME_WRAPPER_ADDRESS}/${unknown.namehash}`, options),
    { instanceOf: HTTPError }
  );
  const message = JSON.parse(body as string)?.message;
  t.is(message, unknown.expect);
  t.is(statusCode, 404);
});
Example #4
Source File: index.test.ts    From ens-metadata-service with MIT License 6 votes vote down vote up
test('get /:contractAddress/:tokenId for empty tokenId', async (t: ExecutionContext<TestContext>) => {
  const {
    response: { statusCode, body },
  }: HTTPError = await t.throwsAsync(
    () => got(`rinkeby/${NAME_WRAPPER_ADDRESS}/`, options),
    {
      instanceOf: HTTPError,
    }
  );
  t.assert(
    (body as string).includes(`Cannot GET /rinkeby/${NAME_WRAPPER_ADDRESS}/`)
  );
  t.is(statusCode, 404);
});
Example #5
Source File: index.test.ts    From ens-metadata-service with MIT License 6 votes vote down vote up
test('raise 404 status from subgraph connection', async (t: ExecutionContext<TestContext>) => {
  const fetchError = {
    message: 'nothing here',
    code: '404',
    statusCode: 404,
  };
  nock(SUBGRAPH_URL.origin)
    .post(SUBGRAPH_URL.pathname, {
      query: GET_DOMAINS,
      variables: {
        tokenId: sub1Wrappertest.namehash,
      },
    })
    .replyWithError(fetchError);
  const {
    response: { body, statusCode },
  }: HTTPError = await t.throwsAsync(
    () =>
      got(`rinkeby/${NAME_WRAPPER_ADDRESS}/${sub1Wrappertest.namehash}`, {
        ...options,
        retry: 0,
      }),
    {
      instanceOf: HTTPError,
    }
  );
  const { message } = JSON.parse(body as string);
  // Regardless of what is the message in subgraph with status 404 code
  // user will always see "No results found."" instead
  t.assert(message.includes('No results found.'));
  t.is(statusCode, fetchError.statusCode);
});
Example #6
Source File: index.test.ts    From ens-metadata-service with MIT License 6 votes vote down vote up
test('raise ECONNREFUSED from subgraph connection', async (t: ExecutionContext<TestContext>) => {
  const fetchError = {
    message: 'connect ECONNREFUSED 127.0.0.1:8000',
    code: 'ECONNREFUSED',
    statusCode: 500,
  };
  nock(SUBGRAPH_URL.origin)
    .post(SUBGRAPH_URL.pathname, {
      query: GET_DOMAINS,
      variables: {
        tokenId: sub1Wrappertest.namehash,
      },
    })
    .replyWithError(fetchError);
    const {
      response: { body, statusCode },
    }: HTTPError = await t.throwsAsync(
      () =>
        got(`rinkeby/${NAME_WRAPPER_ADDRESS}/${sub1Wrappertest.namehash}`, {
          ...options,
          retry: 0,
        }),
      {
        instanceOf: HTTPError,
      }
    );
    const { message } = JSON.parse(body as string);
    // Regardless of what is the message in subgraph with status 404 code
    // user will always see "No results found."" instead
    t.assert(message.includes('No results found.'));
    t.is(statusCode, 404);
  });
Example #7
Source File: index.test.ts    From ens-metadata-service with MIT License 6 votes vote down vote up
test('raise Internal Server Error from subgraph', async (t: ExecutionContext<TestContext>) => {
  const fetchError = {
    message: 'Internal Server Error',
    code: '500',
    statusCode: 500,
  };
  nock(SUBGRAPH_URL.origin)
    .post(SUBGRAPH_URL.pathname, {
      query: GET_DOMAINS,
      variables: {
        tokenId: sub1Wrappertest.namehash,
      },
    })
    .replyWithError(fetchError);
    const {
      response: { body, statusCode },
    }: HTTPError = await t.throwsAsync(
      () =>
        got(`rinkeby/${NAME_WRAPPER_ADDRESS}/${sub1Wrappertest.namehash}`, {
          ...options,
          retry: 0,
        }),
      {
        instanceOf: HTTPError,
      }
    );
    const { message } = JSON.parse(body as string);
    t.assert(message.includes('No results found.'));
    t.is(statusCode, 404);
  });
Example #8
Source File: index.test.ts    From ens-metadata-service with MIT License 6 votes vote down vote up
test('raise timeout from subgraph', async (t: ExecutionContext<TestContext>) => {
  nock(SUBGRAPH_URL.origin)
    .post(SUBGRAPH_URL.pathname, {
      query: GET_DOMAINS,
      variables: {
        tokenId: sub1Wrappertest.namehash,
      },
    })
    .delayConnection(2000) // 2 seconds
    .replyWithError({ code: 'ETIMEDOUT' })
    .persist(false);
  const {
      response: { statusCode },
    }: HTTPError = await t.throwsAsync(
      () =>
        got(`rinkeby/${NAME_WRAPPER_ADDRESS}/${sub1Wrappertest.namehash}`, {
          ...options,
          retry: 0,
        }),
      {
        instanceOf: HTTPError,
      }
    );
    t.assert(statusCode === 404);
  });
Example #9
Source File: index.test.ts    From ens-metadata-service with MIT License 6 votes vote down vote up
test('raise ContractMismatchError', async (t: ExecutionContext<TestContext>) => {
  const {
    response: { body },
  }: HTTPError = await t.throwsAsync(
    () =>
      got(`rinkeby/${NON_CONTRACT_ADDRESS}/${sub1Wrappertest.namehash}`, {
        ...options,
        retry: 0,
      }),
    {
      instanceOf: HTTPError,
    }
  );
  const { message } = JSON.parse(body as string);
  t.assert(
    message ===
      `${NON_CONTRACT_ADDRESS} does not match with any ENS related contract`
  );
});