Use cases of log.Fatal in Golang
Tags: go, programming, tutorial, beginners
Published: 2023-02-10 09:09:33

**The log.Fatal() function is used when something really bad has happened and you just want to exit your program as fast as possible after reporting the error situation.**

In this article we are going to learn about when to use the log.Fatal() in Golang. “The log.Fatal() function is used when something really bad has happened and you just want to exit your program as fast as possible after reporting the error situation.“

Let’s take an example, You have a microservice which uses the environment file, to use that environment file you must load all the variable in that session and for that you’re using a function called LoadEnv(path string) error, which takes the path of the environment file and and returns a error if anything goes wrong, By chance if the provided path is wrong then the function will immediately return back the error that “provided path is wrong” if you’re not going to handle that situation then you might not be able to use the environment variables anymore, so that’s why you’ll need to use the log.Fatal(err) to return back from that situation and terminates your program so you can identify what is causing the error.

Let’s see cover some use cases when to use log.Fatal() function and when not to use log.Fatal() function.

### When to use log.Fatal()?
Below is the possible use cases when you should use log.Fatal() function:

- Always use log.Fatal() for those errors which can crash your server.
- Always use log.Fatal() in your DB connection function, if you’re using a DB then you don’t want your services to fail so it’s better to terminate service and update DB credentials or check why connection with DB is not happening.
- Always use log.Fatal() for those service connection functions which are required to run your server. Example you’re using redis to store data and if the connection with redis is not established then the function that is using the connection can not store or extract information from redis so in connection function always use log.Fatal() in your error conditions.
- When the program encounters an unexpected error condition, such as invalid input from the user, a call to log.Fatal() can be used to terminate the program and report the error.
- When the program is unable to write to a required file, such as a log file, a call to log.Fatal() can be used to terminate the program and report the error.
- When a required configuration file is not found or cannot be read, a call to log.Fatal() can be used to terminate the program and report the error.
Now we have idea when to use log.Fatal() function, It’s time to cover the use cases when not to use log.Fatal() function.

### When not to use log.Fatal()?
Below is the possible use cases when you shouldn’t use log.Fatal() function:

- When the program can continue to execute despite the error. In these cases, it’s better to use log.Print() or log.Panic() to report the error, but allow the program to continue running.
- When the error is recoverable, for example, when the program is unable to connect to a server, it can retry connecting after a certain period of time. In this case, it is not appropriate to use log.Fatal() as it will terminate the program immediately.
- When the error is due to a transient issue, such as a temporary network outage, it might not be appropriate to use log.Fatal() as it can cause the program to terminate unnecessarily.
- When the error is expected and handled by the program, such as invalid input from the user. In these cases, it’s better to use log.Print() or return a specific error message to the user instead of terminating the program with log.Fatal().
- When the error is part of normal operation, such as a request to a non-existing endpoint in a web application, it’s better to return a 4XX or 5XX HTTP status code instead of using log.Fatal() to terminate the program.

### Demonstration of log.Fatal() function
Below is a server code which demonstrates the use of log.Fatal() function in Golang:

```go
package main

import (
    "errors"
    "log"
    "net/http"
    "os"

    "github.com/joho/godotenv"
)

var PORT string

func init() {
    args := os.Args
    if len(args) < 1 {
        log.Fatal(errors.New("no argument provided"))
    }
    err := godotenv.Load(args[1])
    if err != nil {
        log.Fatal("failed to load env file ", err)
    }
}

func main() {
    PORT = os.Getenv("PORT")
    if PORT == "" {
        PORT = "8001"
    }

    server := http.NewServeMux()
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello from Testing Server :)"))
    })

    err := http.ListenAndServe(":"+PORT, server)
    if err != nil {
        log.Fatal("failed to run server", err)
    }
}
```
So as you can see in the code that, I have used the log.Fatal() function alot, first I’ve used it in to check if the argument is not provided then it’ll automatically terminate the program and also tell program that you forget to provide the argument which is required to run this program.

In Second we’re using log.Fatal() to terminate the server if anything goes wrong with godotenv.Load(args[1]) and we’re also passing a message to programmers to understand on which line the code is failing, The root of the problem.

This time we’re using log.Fatal() to terminate our server if anything wrong goes with the http.ListenAndServe() function.

It’s important to note that log.Fatal() is a function that will terminate the program, so use it only when you want your program to not continue to execute.

[Originally article is published](https://programmingeeksclub.com/when-to-use-log-fatal-in-golang/)


You can follow me on these platforms as well:

_My Personal Blogging Website : [Programming Geeks Club](https://programmingeeksclub.com/)_
_My Facebook Page : [Programming Geeks Club](https://www.facebook.com/profile.php?id=100086258693659)_
_My Telegram Channel : [Programming Geeks Club](https://t.me/dpgcl)_
_My Twitter Account : [Kuldeep Singh](https://twitter.com/kusinghofficial)_
_My Youtube Channel: [ProgramminGeeksClub](https://www.youtube.com/channel/UCTpm2yuM55e09RL3WLA0bFg)_