Are these two equivalent error logging? And why?
...
err := ...
log.Fatal(err)
}
vs this version
...
err := ...
if err != nil {
log.Fatal(err)
}
}
Are these two equivalent error logging? And why?
...
err := ...
log.Fatal(err)
}
vs this version
...
err := ...
if err != nil {
log.Fatal(err)
}
}
No, they are not. The latter only log the error when err
object is not nil
. The formal always log the err
object even in the event of no error object (err
== nil
).
so the result of first will be empty output (empty line in terminal) when err == nil
? or it will output nothing in this case?
You’ll get a <nil>
.
err = srv.ListenAndServe()
errorLog.Fatal(err)
the above logs nothing when everithing is ok, and logs error when there’s an error
You get nothing because the server is listening and serving, which it won’t running the following line unless an error bound to happen. Since error is guaranteed, you can use the former style.
FYI, you can test the logic on your side. I tested the former directly with nil
, then error
. The output did show the <nil>
message.
package main
import (
"log"
"errors"
)
func main() {
log.Fatal(nil)
err := errors.New("an error message")
log.Fatal(err)
}
// Output:
// 2009/11/10 23:00:00 <nil>
// Program exited: status 1.
More question for this topic?
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.