'Parsing body in response that is a non-200 Status Code - Typescript/Vue

I have an API call that I am making in my app. In some cases the API will return a non-200 status code with a user friendly message in the body of the response. I have set up a try catch block when calling the API. I am facing some challenges getting the body if a non status is returned.

Response body is a json string.

// example response 403 status code ....
{
"message": "Houston we have a problem"
}
    try {
      const results = [];
      let result = [];
      const response = await ky.get(`${this.state.api_base_url}/${path_parts.join("/")}?${query_parts.map(x => `${x.key}=${x.value}`).join("&")}`);
      result = await response.json();
      context.commit("set200response", result);

    } catch (err) {

    // I have tried each of the following without success
    // this returns undefined
    console.error("Non 200 Message", (err as any).response.data.message);
    console.error("Non 200 Message", (err as any).response.data);
    // this returns the promise object but I can not access its properties 
    console.error((err as any).response.json());

    //this returns the generic message for a non 200 status
    console.error("Generic Message", (err as any).message);
    } finally {
        context.commit("setLoading", false);
    } 
    }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source