Blog |

How to Use errors.WithMessage() in Golang

How to Use <wbr>errors.WithMessage()<wbr> in Golang
Table of Contents

In Golang, the WithMessage() method allows you to annotate errors with an additional message. Often, error values by themselves don’t give enough context to be useful in debugging. Take, for example, Golang’s basic error handling technique:

if err != nil {
        return err
}

In Golang, errors are treated as values, so err contains the error value.

In this situation, a developer could make use of the error package to add context to the code along with the failure path without destroying the original value of the error.

Syntax of WithMessage()

WithMessage() annotates err with a new message. If err is nil, WithMessage() returns nil.

func WithMessage(err error, message string) error

Example One

In the below code, the errors package has been imported first, followed by an errors.New() method is used and returns an error. Each call to New returns a distinct error value in the event that the content is indistinguishable.

package main

import (
    "fmt"

    "github.com/pkg/errors"
)

func main() {
    cause := errors.New("What's the cause?!")
    err := errors.WithMessage(cause, "something unusual has occurred")
    fmt.Println(err)

}

Output

something unusual has occurred: What's the cause?!

Example Two

Let’s see another block of code to understand it even better.

import (
   "database/sql"
   "fmt"
)

func second() error {
   return sql.ErrNoRows
}

func first() error {
   return second()
}

func main() {
   err := first()
   if err == sql.ErrNoRows {
      fmt.Printf("Data error, %+v\n", err)
      return
   }

}

Output

Executing the above code results in the following error:

Data error, sql: no rows in result set

Now the output for the error doesn’t make much sense, so let’s try to add withMessage to it in the next example.

Example of errors.WithMessage

By using the WithMessage() method, the failure path in a developer's code could be given context without changing the error's original value. Let’s see an example of the WithMessage() method.

import (
   "github.com/pkg/errors"
   "database/sql"
   "fmt"
)

func second() error {
   return  errors.Wrap(sql.ErrNoRows, "second failed")

}
func first() error {
   return errors.WithMessage(second(), "first failed")
}

func main() {
   err := first()
   if errors.Cause(err) == sql.ErrNoRows {
      fmt.Printf("Data error, %+v\n", err)
      fmt.Printf("%+v\n", err)
      return
   }}

Now that we’ve used the withMessage() method to add a new message to the error, then we print the err.

Output: Example of errors.WithMessage

The following output is obtained after executing the above code.

Data error, first failed: second failed: sql: no rows in result set
sql: no rows in result set
second failed
main.second
    /usr/three/main.go:11
main.first
    /usr/three/main.go:15
main.main
    /usr/three/main.go:19
runtime.main
..

The errors.WithMessage() method, a crucial component of the error package, makes it easier for the developers to comprehend and debug errors by giving context to the issue with the aid of a message.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Golang errors easier than ever. Try it today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape