DEV Community

Cover image for API Design: Errors

API Design: Errors

Sam Rose on April 02, 2019

Errors are one of the easiest things to overlook when creating an API. Your users will have problems from time to time, and an error is the first t...
Collapse
 
theodesp profile image
Theofanis Despoudis • Edited

What about?

func WithRetry(req *http.Request) (*http.Response, error)  {
    res, err := http.DefaultClient.Do(req) // or pass a client here
    if err != nil {
        if IsRetryable(err) {
            // retry
        } else {
            // bail
        }
    }
    return res, nil
}

func main() {
    req, err := http.NewRequest("GET", "https://example.com", nil)
    if err != nil {
        fmt.Fprintln(os.Stderr, err.Error())
        os.Exit(1)
    }
    res, err := WithRetry(req)
    ...
}
Collapse
 
samwho profile image
Sam Rose • Edited

That looks perfectly reasonable. I was mostly avoiding Go's actual "net/http" package. Not for any particular reason, it's a nice API, just wanted a slightly different approach. :)

Collapse
 
theodesp profile image
Theofanis Despoudis • Edited

I think retries and traffic management flow should be left on the service mesh level.
There is a good read here

istio.io/docs/concepts/traffic-man...

I would also love to see something like that in Go
thepollyproject.org/

Thread Thread
 
samwho profile image
Sam Rose

Definitely good arguments to be made in favour of that, but somewhat outside of the scope of this post. 😀

Collapse
 
gklijs profile image
Gerard Klijs

Rust seems to be pretty similar to go. Most libraries define there 'own' error messages. I have a small library where I also added whether it was retriable (and if the error was cashed). The rust way is to return a result, witch either contains a value or an error. It's up to to user to handle possible error nicely, or not, in witch case the program will crash when there is an error.
In Clojure it's pretty common to just return nil when something went wrong. This is part of the language design, do unless Java where there is a high probability of a Null pointer exception, the result will probably just be that nothing happens. But if you want to, you can throw errors just like in Java. When you do get an error message in Clojure it's usually pretty vague, but work is done to improve on that.