gorilla / mux

Package gorilla/mux is a powerful HTTP router and URL matcher for building Go web servers with 🦍

Home Page:https://gorilla.github.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[question] Is using `log.Fatal(err)` good pattern for logging error and returning 500 Internal Error?

juancki opened this issue · comments

Which one of the following is preferred?

(1) Handling the error:

func handler(w http.ResponseWriter, r *http.Request) {
	_, err := fetchDataFromDB(r)
	if err != nil {
		fmt.Println("handler error 01", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

(2) Or just crashing and letting mux (or the nginx under that) handle it:

func handler(w http.ResponseWriter, r *http.Request) {
	_, err := fetchDataFromDB(r)
	if err != nil {
		log.Fatal(err.Error())
	}
}

I've been using (1) all along.
However, it seems that the second one should be preferred for error tracing, as automatically points to the exact line and the involved functions.

  • Is using log.Fatal(err) good pattern for logging error and returning 500 Internal Error?

Particularly relevant when it is necessary to handle multiple sources of errors in the same HTTP Handler function.

thank you for the confirmation!