Lbryinc errors #85

Merged
anbsky merged 5 commits from lbryinc-errors into master 2021-02-22 18:38:00 +01:00
2 changed files with 29 additions and 19 deletions
Showing only changes of commit eb6bb93500 - Show all commits

View file

@ -46,6 +46,15 @@ type APIResponse struct {
Data *ResponseData `json:"data"`
}
// APIError wraps errors returned by LBRY API server to discern them from other kinds (like http errors).
type APIError struct {
Err error
lyoshenka commented 2021-02-18 18:17:53 +01:00 (Migrated from github.com)
Review

Err can be err

`Err` can be `err`
}
func (e APIError) Error() string {
return fmt.Sprintf("api error: %v", e.Err)
}
// ResponseData is a map containing parsed json response.
type ResponseData map[string]interface{}
@ -133,16 +142,17 @@ func (c Client) Call(object, method string, params map[string]interface{}) (Resp
return rd, err
}
if !ar.Success {
return rd, errors.New(*ar.Error)
return rd, APIError{errors.New(*ar.Error)}
}
return *ar.Data, err
}
// UserMe returns user details for the user associated with the current auth_token
// UserMe returns user details for the user associated with the current auth_token.
func (c Client) UserMe() (ResponseData, error) {
return c.Call(userObjectPath, userMeMethod, map[string]interface{}{})
}
// UserHasVerifiedEmail calls has_verified_email method.
func (c Client) UserHasVerifiedEmail() (ResponseData, error) {
return c.Call(userObjectPath, userHasVerifiedEmailMethod, map[string]interface{}{})
}

View file

@ -7,25 +7,8 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestUserMeWrongToken(t *testing.T) {
c := NewClient("abc", nil)
r, err := c.UserMe()
require.NotNil(t, err)
assert.Equal(t, "could not authenticate user", err.Error())
assert.Nil(t, r)
}
func TestUserHasVerifiedEmailWrongToken(t *testing.T) {
c := NewClient("abc", nil)
r, err := c.UserHasVerifiedEmail()
require.NotNil(t, err)
assert.Equal(t, "could not authenticate user", err.Error())
assert.Nil(t, r)
}
func launchDummyServer(lastReq **http.Request, path, response string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
*lastReq = &*r
@ -74,6 +57,23 @@ func TestRemoteIP(t *testing.T) {
assert.Equal(t, []string{"8.8.8.8"}, req.Header["X-Forwarded-For"])
}
func TestWrongToken(t *testing.T) {
c := NewClient("zcasdasc", nil)
r, err := c.UserHasVerifiedEmail()
assert.Nil(t, r)
assert.EqualError(t, err, "api error: could not authenticate user")
assert.ErrorAs(t, err, &APIError{})
}
func TestHTTPError(t *testing.T) {
c := NewClient("zcasdasc", &ClientOpts{ServerAddress: "http://lolcathost"})
r, err := c.UserHasVerifiedEmail()
assert.Nil(t, r)
assert.EqualError(t, err, `Post "http://lolcathost/user/has_verified_email": dial tcp: lookup lolcathost: no such host`)
}
const userMeResponse = `{
"success": true,
"error": null,