From: Matthias Kruk Date: Mon, 6 Jun 2022 00:06:40 +0000 (+0900) Subject: include/gitlab: Make _gitlab_get() and _gitlab_post() handle errors X-Git-Url: https://git.corax.cc/?a=commitdiff_plain;h=6a30ffd16e3904192256243c43a3573d5bea94c0;p=toolbox-restapis include/gitlab: Make _gitlab_get() and _gitlab_post() handle errors When an API call fails, GitLab usually returns HTTP 200 and a JSON object with an error message. Because HTTP 200 indicates success, _gitlab_get() and _gitlab_post() assume that the call succeeded and do not return an error. This commit modifies _gitlab_get() and _gitlab_post() to check if the received JSON object contains an "error" member, which should not be found in any non-error results. If an "error" member was found, the API call is assumed to have failed. --- diff --git a/include/gitlab.sh b/include/gitlab.sh index 1d21035..bb63659 100755 --- a/include/gitlab.sh +++ b/include/gitlab.sh @@ -45,30 +45,56 @@ _gitlab_urlencode() { } _gitlab_get() { - local token="$1" - local url="$2" + local token="$1" + local url="$2" - if ! curl --silent --location -X GET \ - --header "Private-Token: $token" "$url"; then - return 1 - fi + local res + local error + local description - return 0 + if ! res=$(curl --silent --location -X GET \ + --header "Private-Token: $token" "$url"); then + return 1 + fi + + if ! error=$(json_object_get "$res" "error" 2>/dev/null) || + [[ "$error" == "null" ]]; then + echo "$res" + return 0 + fi + + description=$(json_object_get "$res" "error_description") + + log_error "Gitlab: $error: $description" + return 1 } _gitlab_post() { - local token="$1" - local url="$2" - local data="$3" + local token="$1" + local url="$2" + local data="$3" - if ! curl --silent --location -X POST \ - --header "Private-Token: $token" \ - --header "Content-Type: application/json" \ - --data "$data" "$url"; then - return 1 - fi + local res + local error + local description - return 0 + if ! res=$(curl --silent --location -X POST \ + --header "Private-Token: $token" \ + --header "Content-Type: application/json" \ + --data "$data" "$url"); then + return 1 + fi + + if ! error=$(json_object_get "$res" "error" 2>/dev/null) || + [[ "$error" == "null" ]]; then + echo "$res" + return 0 + fi + + description=$(json_object_get "$res" "error_description") + + log_error "Gitlab: $error: $description" + return 1 } _gitlab_put() {