Work with bugs in Go

I worked with Go for a while and still don’t know how I work with bugs.

Even the standard library has many ways to deal with errors (some do not even allow checking errors without resorting to string matching).

I recently read Dave Cheney's error checking blog post . It sounds like a step in the right direction, but it’s still very difficult for me to really use it.

Let's say I made a package athat accesses a third-party REST API (for example, Facebook graphics). I would like this package to display the functions corresponding to the API functions - let's say GetUser.

A call GetUsercan have a number of results:

  • Success
  • Failed due to request failure, for example, a third-party API down.
  • The third-party API returned an error (for example, the user was not found)
  • Dysfunctional response or similar failure

The error statement for behavior works very well in the second case. However, it is not suitable for distinguishing between the third and fourth cases.

In my current case, my own REST API is used, which uses this first package. In this case, I would like to bring back the answers 200 OK, 503 Service Unavailable, 400 Bad Request, 500 Internal Server Errorrespectively, to the possible outcomes.

What would be a good general approach to solving this problem without having to include return HTTP response codes or the like from the package a?

+4
source share
2 answers

, , , , .

, , :

, .

, - , , Internal() bool, Temporary() bool, .

, , .

, .

Ainar-G answer .

0

, " ", , . .

type SerializationError struct { Error error }
func (err SerializationError) Error() string { return err.Error.Error() }

type HTTPError struct { Error error }
// ...

API:

b, err := json.Marshal(v)
if err != nil {
     return nil, SerializationError{err}
}

// ...

resp, err := client.Post(url, ct, body)
if err != nil {
    return nil, HTTPError{err}
}

:

err := client.GetUser(id)
switch err.(type) {
case SerializationError:
    // respond with 400
case HTTPError:
    // respond with 500
// etc.
}
+4

Source: https://habr.com/ru/post/1660798/


All Articles