Are these equivalent?

Are these two equivalent error logging? And why?

     ...
     err := ...
     log.Fatal(err)
}

vs this version

     ...
     err := ...
     if err != nil {
          log.Fatal(err)
     }
}
2 Likes

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

1 Like

so the result of first will be empty output (empty line in terminal) when err == nil? or it will output nothing in this case?

2 Likes

You’ll get a <nil>.

1 Like
err = srv.ListenAndServe()
errorLog.Fatal(err)

the above logs nothing when everithing is ok, and logs error when there’s an error

2 Likes

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.
2 Likes

More question for this topic?

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.