Go Custom Error Types

From NovaOrdis Knowledge Base
Revision as of 21:50, 28 December 2023 by Ovidiu (talk | contribs) (→‎Overview)
Jump to navigation Jump to search

Internal

Overview

The values of any type that implements the error interface can be used as errors. An improvement of error types over error values is their ability to provide more context: instead of a string that contains a human-readable error message, the error instance may carry additional information like (for example) line number, user IDs, etc., which can be used programmatically by error handling code. Error types may even wrap an underlying error in the new type to provide more context. See os.PathError for such an example. As mentioned in the Error Basics section, if context elements need to be processed programmatically as part of the program logic, use a custom type instead of parsing the error message.

As long as the specific type is not used in error handling, in type assertion if and switch statements, custom error types values can be used as any other generic error values and do not introduce additional complications.

However, the problems start when error types must be made public, so the caller can use a type assertion or a type switch. If your code implements an interface whose contract requires a specific error type, all implementors of that interface need to depend on the package that defines the error type. This knowledge of a package's types creates a strong coupling with the caller, making for a brittle API. This is a reason to avoid error types, at least to avoid making them part of the public API.

An Example of a Custom Error Type