3

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).

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
tlebrun06
  • 81
  • 1
  • 7
  • you need to update more about the main func and error message. Basically, you can use recover in go. For example, defer func() { if r := recover(); r != nil { fmt.Println("Recovered in f", r) } }(). Ref: https://blog.golang.org/defer-panic-and-recover – nguyenhoai890 May 08 '20 at 08:24
  • 1
    **Your** **own** **code** crashes the server! If you call log.Fatal your server is terminated immediately. Just don't do that. It is a bit like asking: "How to avoid the pain when It hit my thumb with a hammer?": Do not hit your thumb with a hammer. One more good advice. Do not guess what a function does but literally _always_ read their **full** documentation, including the **whole** package documentation. Unlike e.g. Javadoc the godoc contains valuable and _needed_ information. – Volker May 08 '20 at 08:49
  • 1
    Oh my god I would have never guessed a log function to make an exit ... too much expecting behaviour , not enough reading doc as you said, thanks! – tlebrun06 May 08 '20 at 09:10

2 Answers2

8

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())
Oleg Butuzov
  • 4,795
  • 2
  • 24
  • 33
4

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

tlebrun06
  • 81
  • 1
  • 7