← All Exercises

Sentinel and Wrapped Errors

intermediatego~25min

Background

Sentinel errors support errors.Is comparisons across wrapping layers; typed errors support errors.As extraction of structured details.

Problem

Implement ErrNotFound, ValidationError{Field}, loadUser(id), and classify(err). loadUser returns Ada for id 7, a ValidationError for id <= 0, and a wrapped ErrNotFound for any other positive id. classify maps nil to ok, validation errors to validation:<field>, ErrNotFound to not-found, and anything else to unknown.

Input

A user ID passed to loadUser and the resulting error passed to classify.

Output

A classification string for each error, plus proof that errors.Is sees ErrNotFound through wrapping.

Sample tests

Sample 1

Input: ids 7, 8, and 0
Expected: Ada ok; not-found; validation:id

Sample 2

Input: id 8, errors.Is(err, ErrNotFound)
Expected: true

Your solution

Learning objective

Design error APIs that callers can classify without matching error strings.