]> git.corax.cc Git - toolbox-restapis/commitdiff
include/gitlab: Make _gitlab_get() and _gitlab_post() handle errors
authorMatthias Kruk <m@m10k.eu>
Mon, 6 Jun 2022 00:06:40 +0000 (09:06 +0900)
committerMatthias Kruk <m@m10k.eu>
Mon, 6 Jun 2022 00:15:54 +0000 (09:15 +0900)
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.

include/gitlab.sh

index 1d2103575ffc1ce5f3f9ac2a6556c7ec60f4ca90..bb6365941ec86d54ea645336a15e9987f07e3f7c 100755 (executable)
@@ -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() {