12/04/2026 18:15pm

EP.9 Go and Error Handling & Logging - Mastering Error Management Like a Pro!
#Go
#Error Handling
#Logging
#Custom Errors
#defer
#application development
#Superdev School
Go and Error Handling & Logging - Mastering Error Management Like a Pro!
Errors are a part of programming, and in Go, we emphasize effective error handling.
What is Error Handling in Go?
Go does not use Exceptions like other languages but focuses on error checking through the return value of functions. This makes error management clearer and easier to control.
Example of a function returning an Error:
package main
import (
"errors"
"fmt"
)
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Result:", result)
}
Creating Custom Errors
We can create our own specific errors to better describe events:
var ErrInvalidInput = errors.New("invalid input provided")
func checkInput(input int) error {
if input < 0 {
return ErrInvalidInput
}
return nil
}
Logging in Go
Logging is an essential part of monitoring and tracking errors that occur in the system.
Example of using Log:
package main
import (
"log"
"os"
)
func main() {
file, err := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
log.SetOutput(file)
log.Println("Application started")
log.Println("Something happened")
}
Using defer for Resource Management
The defer statement in Go allows us to properly close files or other resources, even when errors occur.
Example:
func main() {
file, err := os.Open("data.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close() // ปิดไฟล์เมื่อใช้งานเสร็จ
}