Handle error HTTPBuilder groovy

I have this code snippet which will call an API and return a list of Users in List format:

return http.request(Method.GET, ContentType.JSON) {
    uri.path = USERS_ENDPOINT
} as List<Map>

The API returns a JSON array of users like this:

[
  {
    name: "John",
    address: "Mars",
    picture: "https://example.com"
  },
  {
    name: "Doe",
    address: "Earth",
    picture: "https://example.com"
  }
]

That example will work perfectly if there is no problem with the API. Now I want to handle the case where this API returns an error (such as 401, 500):

  • If the API call is successful, return the data as List immediately
  • If there is any problem, do something and go to the next line

I have tried this but it does not work:

http.request(Method.GET, ContentType.JSON) {
    uri.path = USERS_ENDPOINT

    response.success { res, reader ->
        return reader as List<Map>
    }

    response.failed {
        // do somthing here, a logging for example
        log.warn "Failed"
    }
}

// the next statement I want to execute after the API call has been failed

Any idea on this?

well what output ? Hard to say without the example.

The output of this API is just a JSON Array, I can say it looks like this:

[
  {
    name: "John",
    address: "Mars",
    picture: "https://example.com"
  }
]