It's unavoidable to see some errors in production environments even though every programmer tries their best to eliminate bugs. Every human makes mistakes, what is important is we should have solution to monitor and track error. Error handling and logging is an area we should pay attention to. If we place sophisticated error handling and logging logic in our code, we can locate and fix error fast when we detect it.
Error in Go
While other languages move error handling out of the code flow, Go considers errors a natural part of the program flow. If a function encounters an error, it returns that error alongside other return values. The caller has the duty to check this error and handle it accordingly.
The error type is a built-in interface
In Go (Golang), an interface is a type that specifies a set of method signatures. It defines behavior by declaring a collection of method prototypes, and any type that implements those methods satisfies the interface.
Return an error
Define a custom error
Include stacktrace info
Wrap an error
Unwrap an error
Testing for Specific Error Types
Joined Errors
Logging in Go
Slog was released in Go V1.21.
Three main types in log/slog
Logger: the logging "frontend" which provides level methods such as (Info() and Error()) for recording events of interest.
Record: a representation of each self-contained log object created by a Logger.
Handler: an interface that, once implemented, determines the formatting and destination of each Record. Two built-in handlers are included in the log/slog package: TextHandler and JSONHandler for key=value and JSON output respectively.
Customizing the default logger
Output key value pairs
Child loggers
Child loggers can include additional fields for all output.
Slog Levels
The log/slog package provides four log levels by default, with each one associated with an integer value: DEBUG (-4), INFO (0), WARN (4), and ERROR (8).