liveBook · Manning

Error type

As explained in Go in Practice, Second Edition

An error type is a data type whose values represent failure conditions and may carry information or behavior for reporting and handling those failures.

In Go, an error type represents a failure through the error interface, whose Error() string method supplies a message. A custom type adds structured information or behavior so callers can respond to specific failures. section 4.1.2

Create a custom error when a plain message is insufficient:

  • Define fields that describe the failure, such as Message, Line, and Char for a parser error. section 4.1.2
  • Implement Error() string by formatting those fields into a readable message. section 4.1.2
  • Return the value as an error, allowing callers to inspect additional details or handle error kinds separately. section 4.1.2
  • For HTTP APIs, convert unexpected status codes and custom error responses into an error carrying HTTPCode, Code, and Message. section 11.2.2
Listing 4.7 Parse error
type ParseError struct {
     Message    string        #1
     Line, Char int             #2
}
func (p *ParseError) Error() string {                         #3
     format := "%s o1n Line %d, Char %d"                      #3
     return fmt.Sprintf(format, p.Message, p.Line, p.Char)    #3
}                                                             #3

Use the ParseError listing to see a concrete struct implement the error interface with location-aware diagnostics. section 4.1.2

How Go in Practice, Second Edition covers it

How deep it goes
Explains the error interface, implements structured parser and HTTP errors, and stops short of broader type-system internals.
Examples
Demonstrates ParseError diagnostics and conversion of non-success HTTP responses into structured errors.
What it assumes
Assumes basic Go functions and structs while establishing the error interface through its single Error method.
What you can do after
Build custom Go errors that carry structured diagnostics and handle unexpected HTTP responses explicitly.
How it connects
Connects error handling with interfaces, parsers, HTTP status codes, MIME types, and panics.

Also explained in

Compare how 5 books explain error type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.