Introduce APIError type and make ErrorEvent.Err public

This makes it a little bit easier to act on API errors that happen while
streaming.
This commit is contained in:
Alexander Bakker 2023-03-11 12:10:46 +01:00
parent 9faaa4f0dc
commit 972ffb4771
6 changed files with 49 additions and 24 deletions

View file

@ -3,12 +3,26 @@ package mastodon
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
)
type APIError struct {
prefix string
Message string
StatusCode int
}
func (e *APIError) Error() string {
errMsg := fmt.Sprintf("%s: %d %s", e.prefix, e.StatusCode, http.StatusText(e.StatusCode))
if e.Message == "" {
return errMsg
}
return fmt.Sprintf("%s: %s", errMsg, e.Message)
}
// Base64EncodeFileName returns the base64 data URI format string of the file with the file name.
func Base64EncodeFileName(filename string) (string, error) {
file, err := os.Open(filename)
@ -41,15 +55,18 @@ func Base64Encode(file *os.File) (string, error) {
func String(v string) *string { return &v }
func parseAPIError(prefix string, resp *http.Response) error {
errMsg := fmt.Sprintf("%s: %s", prefix, resp.Status)
res := APIError{
prefix: prefix,
StatusCode: resp.StatusCode,
}
var e struct {
Error string `json:"error"`
}
json.NewDecoder(resp.Body).Decode(&e)
if e.Error != "" {
errMsg = fmt.Sprintf("%s: %s", errMsg, e.Error)
res.Message = e.Error
}
return errors.New(errMsg)
return &res
}