From e6183ddfa3afa0f7504492198d2b6a463ead8dfa Mon Sep 17 00:00:00 2001 From: milarin Date: Mon, 9 Oct 2023 13:48:09 +0200 Subject: [PATCH] handle error messages --- .gitignore | 1 + api.go | 4 ++++ api_error.go | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 .gitignore create mode 100644 api_error.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..efe1bd2 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +api_test.go \ No newline at end of file diff --git a/api.go b/api.go index fb63f02..ad64082 100644 --- a/api.go +++ b/api.go @@ -49,6 +49,10 @@ func request[T any](api *Api, query string, vars map[string]interface{}, respObj } defer resp.Body.Close() + if resp.StatusCode != 200 { + return handleError(resp) + } + //data, _ := ioutil.ReadAll(resp.Body) //fmt.Println(string(data)) diff --git a/api_error.go b/api_error.go new file mode 100644 index 0000000..94f6245 --- /dev/null +++ b/api_error.go @@ -0,0 +1,32 @@ +package anilist + +import ( + "encoding/json" + "errors" + "net/http" +) + +type apiError struct { + Message string `json:"message"` + Status int `json:"status"` +} + +type apiErrResp struct { + Errors []apiError `json:"errors"` +} + +func handleError(resp *http.Response) error { + respObj := &apiErrResp{} + + dec := json.NewDecoder(resp.Body) + err := dec.Decode(respObj) + if err != nil { + return err + } + + if len(respObj.Errors) == 0 { + return errors.New("unknown API error") + } + + return errors.New(respObj.Errors[0].Message) +}