Go Custom Error Types: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 4: Line 4:
=Overview=
=Overview=


The values of any type that implements the <code>[[#The_error_Type_and_error_Values|error]]</code> 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 <code>[https://pkg.go.dev/io/fs#PathError os.PathError]</code> for such an example.  As mentioned in the [[Go_Language_Error_Handling#Do_Not_Program_Around_Error_Message|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.
The values of any type that implements the <code>[[#The_error_Type_and_error_Values|error]]</code> 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 <code>[https://pkg.go.dev/io/fs#PathError os.PathError]</code> for such an example.  As mentioned in the [[Go_Language_Error_Handling#Do_Not_Program_Around_Error_Message|Error Basics]] section, if the error 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 [[Go_Type_Assertions#Type_Assertion|type assertion]] <code>if</code> and <code>switch</code> statements, custom error types values can be used as any other generic error values and do not introduce additional complications.  
As long as the specific type is not used in error handling, in [[Go_Type_Assertions#Type_Assertion|type assertion]] <code>if</code> and <code>switch</code> statements, custom error types values can be used as any other generic error values and do not introduce additional complications.  

Revision as of 23:41, 28 December 2023

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 the error 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.

Type Aliases as Error Types

If we need to propagate just one specific value with an error, so we can programmatically handle that value as part of subsequent error handling, aliasing the value's type and turning it into an error type by making it implement the error interface is a pattern that can be used.

For example, if we want to recover an invalid value passed to a square root function sqrt() function, we can alias float64 to NegaativeSqrtError and have the type implement the error interface:

type NegativeSqrtError float64

// Error makes NegativeSqrtError type implement the error interface
func (f NegativeSqrtError) Error() string {
  return fmt.Sprintf("math: square root of a negative number %g", float64(f))
}

func sqrt(arg float64) (float64, error) {
  if arg < 0 {
    return -1, NegativeSqrtError(arg)
  }
  return math.Sqrt(arg), nil
}

...

r, err := sqrt(-1)
if err != nil {
  _, assertionTrue := err.(NegativeSqrtError)
  if assertionTrue {
    fmt.Printf("%v\n", err)
  } else {
    fmt.Println("other kind of error")
  }
} else {
  fmt.Println(r)
}

Structs as Error Types

type SyntaxError struct {
  line   int
  column int
  msg    string
}

// Error makes SyntaxError type implement the error interface
func (e SyntaxError) Error() string {
  return fmt.Sprintf("[%d, %d]: %s", e.line, e.column, e.msg)
}

func parse() error {
 ...
 return SyntaxError{10, 10, "missing identifier"}
 ...
}

...
err := parse()
if _, assertionTrue := err.(SyntaxError); assertionTrue {
  fmt.Printf("%s\n", err)
}