fix: print error messages from instance
If an error occurs when sending a request to an instance, try and decode and print the error message back to the user.
This commit is contained in:
parent
e5eb2d72a8
commit
d52bb3fdf4
2 changed files with 55 additions and 4 deletions
|
@ -123,10 +123,25 @@ func (g *Client) sendRequest(method string, url string, requestBody io.Reader, o
|
|||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusBadRequest {
|
||||
return fmt.Errorf(
|
||||
"did not receive an OK response from the GoToSocial server: got %d",
|
||||
response.StatusCode,
|
||||
)
|
||||
message := struct {
|
||||
Error string `json:"error"`
|
||||
}{
|
||||
Error: "",
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(response.Body).Decode(&message); err != nil {
|
||||
return ResponseError{
|
||||
StatusCode: response.StatusCode,
|
||||
Message: "",
|
||||
MessageDecodeErr: err,
|
||||
}
|
||||
}
|
||||
|
||||
return ResponseError{
|
||||
StatusCode: response.StatusCode,
|
||||
Message: message.Error,
|
||||
MessageDecodeErr: nil,
|
||||
}
|
||||
}
|
||||
|
||||
if object == nil {
|
||||
|
|
36
internal/client/errors.go
Normal file
36
internal/client/errors.go
Normal file
|
@ -0,0 +1,36 @@
|
|||
// SPDX-FileCopyrightText: 2024 Dan Anglin <d.n.i.anglin@gmail.com>
|
||||
//
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package client
|
||||
|
||||
import "fmt"
|
||||
|
||||
type ResponseError struct {
|
||||
StatusCode int
|
||||
Message string
|
||||
MessageDecodeErr error
|
||||
}
|
||||
|
||||
func (e ResponseError) Error() string {
|
||||
if e.MessageDecodeErr != nil {
|
||||
return fmt.Sprintf(
|
||||
"received HTTP code %d from the instance but was unable to decode the error message: %v",
|
||||
e.StatusCode,
|
||||
e.MessageDecodeErr,
|
||||
)
|
||||
}
|
||||
|
||||
if e.Message == "" {
|
||||
return fmt.Sprintf(
|
||||
"received HTTP code %d from the instance but no error message was provided",
|
||||
e.StatusCode,
|
||||
)
|
||||
}
|
||||
|
||||
return fmt.Sprintf(
|
||||
"message received from the instance: (%d) %q",
|
||||
e.StatusCode,
|
||||
e.Message,
|
||||
)
|
||||
}
|
Loading…
Reference in a new issue