anttiviljami / react-openapi-client

Consume OpenAPI-enabled APIs with React Hooks
MIT License
57 stars 10 forks source link

add response on error catch #41

Open jokiefer opened 2 years ago

jokiefer commented 2 years ago

Status quo

currently the response state variable is undefined if any error occurs.

const operationMethod: UnknownOperationMethod = useCallback(
    async (...params) => {
      setLoading(true);
      const client = await api.getClient();
      let res: AxiosResponse;
      try {
        res = await client[operationId](...params);
        setResponse(res);
        setData(res.data);
      } catch (err) {
        setError(err as AxiosError);
      }
      setLoading(false);
      return res;
    },
    [setLoading, setData, setError],
  );

Client errors like bad request (http 400) with server side error messages are missing. Without that it is not possible to handle errors on client side.

jokiefer commented 2 years ago

drop this... the response is part of the error. The reason why i didn't find it directly is that there is a type mismatch:

// file: react-openapi-client/useOperationMethod.d.ts
import { UnknownOperationMethod, OpenAPIClientAxios, AxiosResponse } from 'openapi-client-axios';
export declare function useOperationMethod(operationId: string): [
    UnknownOperationMethod,
    {
        loading: boolean;
        error?: Error;
        data?: any;
        response: AxiosResponse;
        api: OpenAPIClientAxios;
    }
];

Fixing the typescript mismatch:

const axiosError = error as AxiosError;
console.log('response', axiosError?.response);