[question] Is using `log.Fatal(err)` good pattern for logging error and returning 500 Internal Error?
juancki opened this issue · comments
Juan Carlos Gómez commented
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?
Juan Carlos Gómez commented
Particularly relevant when it is necessary to handle multiple sources of errors in the same HTTP Handler function.
Matt Silverlock commented
log.Fatal() calls os.Exit() and will terminate your server.
You likely don’t want that to happen on any HTTP 500 error.
If you want to handle errors, you can:
1. Use http.Error to return a status code and error body
2. Implement your own custom handler type:
https://blog.questionable.services/article/http-handler-error-handling-revisited/
Juan Carlos Gómez commented
thank you for the confirmation!