In our previous article, we learned how to setup a connection to the Apple App Store Connect API with Golang. Today, we are going to refine this a little by adding support for parsing the error responses.

If you issue an incorrect request or something goes wrong, you'll get a response similar to this:

{
    "errors": [
        {
            "status": "404",
            "code": "NOT_FOUND",
            "title": "The specified resource does not exist",
            "detail": "The path provided does not match a defined resource type."
        }
    ]
}

As you can see based on the JSON data, you can get multiple errors for a single request. I defined the error parsing like this:

package main

import (
  "fmt"
  "strings"
)

type ErrorResponse struct {
  Errors []Error `json:"errors"`
}

func (e *ErrorResponse) Error() string {
  msgs := []string{}
  for _, err := range e.Errors {
    msgs = append(msgs, err.Error())
  }
  return strings.Join(msgs, "\n")
}

type Error struct {
  Code   string `json:"code"`
  Status string `json:"status"`
  ID     string `json:"id"`
  Title  string `json:"title"`
  Detail string `json:"detail"`
}

func (e *Error) Error() string {
  return fmt.Sprintf("%s | %s | %s", e.Status, e.Title, e.Detail)
}

So, after we have obtained the bytes from the response, we can check the status code of the HTTP request. If it's not a code between 200 and 299, we consider that the response will contain an error. We can parse it like this:

resp, err := client.Do(req)
if err != nil {
  log.Fatal(err)
}
defer resp.Body.Close()

bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
  log.Fatal(err)
}

if c := resp.StatusCode; c < 200 || c > 299 {
  var errResponse ErrorResponse
  if err := json.Unmarshal(bytes, &errResponse); err != nil {
    log.Fatal(err)
  }
  log.Fatal(errResponse)
}

We first read all the bytes as we want to store them for later one. You can decode the JSON directly from the response if you want to, but I prefer to keep it in a variable for now. We then check the status code and parse the JSON into an ErrorResponse struct. Since ErrorResponse implements the Error interface, we can simply log it as an error. The output is then something like:

2020/12/20 15:02:28 404 | The specified resource does not exist | The path provided does not match a defined resource type.

Next time, we'll look into how to read a successful response.