Home >Backend Development >Golang >How Can I Check the Type of a Custom Error in Go?

How Can I Check the Type of a Custom Error in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-12-25 20:43:19819browse

How Can I Check the Type of a Custom Error in Go?

Customizing Error Types in Go

Enriching your Go applications with custom error types enhances error handling, but manipulating these custom types can be challenging. Let's delve into the issue of checking for the type of a custom error.

The Problem

Consider the following custom error type:

type ModelMissingError struct {
    msg string // description of error
}

func (e *ModelMissingError) Error() string { return e.msg }

Within a method, we can throw a custom error:

return Model{}, &ModelMissingError{"no model found for id"}

The Query

To determine if an error is a specific custom type, we need to check its type. However, the approach if err == model.ModelMissingError fails.

The Solution

Go provides the comma ok idiom to check for type assertion:

serr, ok := err.(*model.ModelMissingError)

This statement asserts that the error variable err holds the model.ModelMissingError type and assigns the underlying value to the variable serr. If err does not hold the expected type, the statement will return nil for serr and false for ok.

By using the comma ok idiom, we can efficiently verify the type of a custom error and handle it accordingly.

The above is the detailed content of How Can I Check the Type of a Custom Error in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn