N
N
Nikita Krasnikov2019-04-11 12:01:11
go
Nikita Krasnikov, 2019-04-11 12:01:11

How to handle erroneous API response to go?

How to correctly handle an erroneous response received from the API?
For example, with a correct request, a correct json model is returned, let's call it User, which has a structure in Go:

type User struct {
  Country     string `json:"country"`
  Login       string `json:"login"`
  DisplayName string `json:"display_name"`
  UID         string `json:"uid"`
}

If the request is incorrect, the Error json model is returned, the structure in Go is:
type Error struct {
  Message     string `json:"message"`
  Description string `json:"description"`
  Error       string `json:"error"`
}

There is a function:
func (c *Client) GetUser(login string) (User,error) {
  // ..body
}

Which should return the User structure, but what to return in case of an error. I thought in the Error structure to implement the error interface and pass an erroneous response directly through error.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
uvelichitel, 2019-04-11
@YekitKsv

I thought in the Error structure to implement the error interface and pass an erroneous response directly through error.
Quite right.
So
func(e Error) Error() string{
    return e.Message
}

or so
type Error struct {
  Message     string `json:"message"`
  Description string `json:"description"`
  Error       string `json:"error"`
  error
}

D
devalone, 2019-04-11
@devalone

func (c *Client) GetUser(login string) (*User,error) {
  
  // ...
  
  return nil, err
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question