Go Errors
Go Errors is a package for handling errors in Go. It provides a simple and flexible way to create, handle and manage
errors in your code.
Installation
To use Go Errors in your Go project, you need to install it using Go modules. Run the following command in your
terminal:
go get github.com/startcodextech/goerrors
Usage
Creating an error
To create an error, you can use the New function. It takes a message and an optional code as arguments and returns a new
error:
Parameters
- Message (string): The message of the error.
- Code (string): The code of the error. This is optional.
- Message technical (string): The technical message of the error. This is optional.
err := goerrors.New("An error occurred", "ERR-001", "An error occurred while processing your request")
Use builder to create an error:
err := goerrors.NewBuild().
Code("ERR-002").
Message("test").
Technical("test").
Build()
Converting an error to a Err
To convert an error to a Err, you can use the FromError function. It takes an error as an argument and returns a Err:
err := goerrors.FromError(err)
so that you can have the structure completely converted, the error must have the following format:
Code: %s Message: %s Technical: %s
Checking if an error is an instance of another error
To check if an error is an instance of another error, you can use the Is function. It takes an error and an instance of
an error as arguments and returns a boolean:
myErr := goerrors.New("An error occurred", "ERR-001")
...
data, err := db.GetData()
if errors.Is(err, myErr) {
// Do something
}
The As function is used to extract information from custom errors that might be wrapped in other errors. Here is an
example showing how to use errors. How to extract a custom error type:
myErr := goerrors.New("An error occurred", "ERR-001")
...
data, err := db.GetData()
if errors.As(err, myErr) {
// Do something
}
Handling an error
To handle an error, you can use the DeferError function. It takes a callback function as an argument and calls it with
the recovered error and stack trace:
goerror.DeferError(func (err error, stackTrace string) {
log.Printf("Error: %v\nStack Trace: %s", err, stackTrace)
})
Getting the stack trace
To get the stack trace of an error, you can use the GetStackTrace function. It returns a string with the stack trace of
the error:
stackTrace := err.GetStackTrace()
Getting the error message and code
To get the message and code of an error, you can use the Message and Code methods respectively:
message := err.GetError()
code := err.GetCode()
thechnical := err.GetTechnical()
License
Go Errors is licensed under the BSD3 License. See LICENSE for more information.