How to avoid Golang server (Gin Gonic) to crash on INTERNAL_ERROR

Viewed 2923

first of all : I'm new to Go, I come from years of java development.

I have developed a little REST API using Gin Gonic. One of my endpoint occasionally (so I can't reproduce on demand) crashes during an HTTP Get to an external API I don't manage. The error displayed is something like :

stream error: stream ID 4; INTERNAL_ERROR

An extract from the code crashing :

client := &http.Client{}
req, err := http.NewRequest("GET", apiUrl, nil)
if err != nil{
    log.Fatal(err)
    return result, err
}
resp, err := client.Do(req)
if err != nil {
    log.Fatal(err)
    return result, err
}
defer resp.Body.Close()

This crashes my server and stops it.

I don't understand what's happening, I'm handling all the errors in the code, so it looks like an uncaught exception comparing to java, but I don't know how to catch that error and keep my server running (I don't care about avoid the error itself, I just want my server to keep going).

2 Answers

In gin-gonic you can use gin.Recover() middleware that helps your application to recover from panic.

You can use instantiation via gin.New() or via gin.Default() (it's already included)

handlers := gin.New()
handlers.Use(gin.Recovery())

log.Fatal makes an exit (dumb me, thanks Volker)

Related