2020-01-02 05:39:52 +00:00
|
|
|
package httputil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
2021-11-29 20:28:51 +00:00
|
|
|
|
|
|
|
"github.com/diamondburned/arikawa/v3/utils/json"
|
2020-01-02 05:39:52 +00:00
|
|
|
)
|
|
|
|
|
2021-11-29 20:28:51 +00:00
|
|
|
// JSONError is returned if the request responds with an invalid JSON.
|
2020-01-02 05:39:52 +00:00
|
|
|
type JSONError struct {
|
2020-05-03 21:02:03 +00:00
|
|
|
err error
|
|
|
|
}
|
|
|
|
|
|
|
|
func (j JSONError) Error() string {
|
|
|
|
return "JSON decoding failed: " + j.err.Error()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (j JSONError) Unwrap() error {
|
|
|
|
return j.err
|
2020-01-02 05:39:52 +00:00
|
|
|
}
|
|
|
|
|
2021-11-29 20:28:51 +00:00
|
|
|
// RequestError is returned if the request fails to be done, i.e. the server is
|
|
|
|
// never reached.
|
2020-01-02 05:39:52 +00:00
|
|
|
type RequestError struct {
|
2020-05-03 21:02:03 +00:00
|
|
|
err error
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r RequestError) Error() string {
|
2020-05-16 21:14:49 +00:00
|
|
|
return "request failed: " + r.err.Error()
|
2020-05-03 21:02:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r RequestError) Unwrap() error {
|
|
|
|
return r.err
|
2020-01-02 05:39:52 +00:00
|
|
|
}
|
|
|
|
|
2021-11-29 20:28:51 +00:00
|
|
|
// HTTPError is returned if the server responds successfully with an error of
|
|
|
|
// any kind.
|
2020-01-02 05:39:52 +00:00
|
|
|
type HTTPError struct {
|
|
|
|
Status int `json:"-"`
|
|
|
|
Body []byte `json:"-"`
|
|
|
|
|
|
|
|
Code ErrorCode `json:"code"`
|
2021-11-29 20:28:51 +00:00
|
|
|
Errors json.Raw `json:"errors,omitempty"`
|
2020-01-02 05:39:52 +00:00
|
|
|
Message string `json:"message,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (err HTTPError) Error() string {
|
|
|
|
switch {
|
2021-11-29 20:41:13 +00:00
|
|
|
case err.Errors != nil:
|
2021-11-29 20:28:51 +00:00
|
|
|
return fmt.Sprintf("Discord %d error: %s: %s", err.Status, err.Message, err.Errors)
|
|
|
|
|
2020-01-02 05:39:52 +00:00
|
|
|
case err.Message != "":
|
2020-12-12 01:58:52 +00:00
|
|
|
return fmt.Sprintf("Discord %d error: %s", err.Status, err.Message)
|
2020-01-02 05:39:52 +00:00
|
|
|
|
|
|
|
case err.Code > 0:
|
|
|
|
return fmt.Sprintf("Discord returned status %d error code %d",
|
|
|
|
err.Status, err.Code)
|
|
|
|
|
|
|
|
case len(err.Body) > 0:
|
|
|
|
return fmt.Sprintf("Discord returned status %d body %s",
|
|
|
|
err.Status, string(err.Body))
|
|
|
|
|
|
|
|
default:
|
|
|
|
return "Discord returned status " + strconv.Itoa(err.Status)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type ErrorCode uint
|