Skip to content

Commit

Permalink
Merge pull request #495 from lifeomic/better-log
Browse files Browse the repository at this point in the history
fix: improve dev log message for failed requests
  • Loading branch information
swain authored Dec 7, 2023
2 parents 2d13779 + 3063f80 commit 57fd8e0
Showing 1 changed file with 35 additions and 2 deletions.
37 changes: 35 additions & 2 deletions src/hooks/useHttpClient.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import React, { createContext, useContext, useMemo } from 'react';
import axios, { AxiosInstance, RawAxiosRequestHeaders } from 'axios';
import axios, {
AxiosError,
AxiosInstance,
RawAxiosRequestHeaders,
} from 'axios';
import { useAuth } from './useAuth';
import { APIClient } from '@lifeomic/one-query';
import { RestAPIEndpoints } from '../types/rest-types';
Expand Down Expand Up @@ -32,6 +36,32 @@ const HttpClientContext = createContext<HttpClient>({
let requestInterceptorId: number;
let responseInterceptorId: number;

/* istanbul ignore next */
const createHumanReadableFailureMessage = (error: AxiosError) => {
const lines: string[] = ['HTTP Request Failed:'];

if (!error.config) {
lines.push(' No request config found.');
return lines.join('\n');
}

const method = error.config.method?.toUpperCase() ?? '<unknown method>';
const baseUrl = error.config.baseURL ?? '<unknown base url>';
const url = error.config.url ?? '<unknown url>';

const status = error.response?.status ?? '<unknown>';

const data = error.response?.data
? JSON.stringify(error.response.data, null, 2)
: '<no response data>';

lines.push(` Endpoint: ${method} ${baseUrl}${url}`);
lines.push(` Response Status: ${status}`);
lines.push(` Response Data: ${data}`);

return lines.join('\n');
};

/**
* The HttpClientContextProvider's job is to provide an HTTP client that
* takes care of things like managing the HTTP Authorization header, error
Expand Down Expand Up @@ -83,7 +113,10 @@ export const HttpClientContextProvider = ({
async function (error: Error) {
if (axios.isAxiosError(error)) {
if (__DEV__ && process.env.NODE_ENV !== 'test') {
console.warn('Request Failed: ', error.toJSON());
console.log(createHumanReadableFailureMessage(error));
console.warn(
'An HTTP request failed. See the Metro logs for details.',
);
}

if (error.response?.status === 401) {
Expand Down

0 comments on commit 57fd8e0

Please sign in to comment.