Errors Are Part of Your API: Practices for Library Authors
Callers write code against your errors as much as against your return values. They catch specific types, compare codes and sometimes parse messages. That makes error behaviour a public interface, with the same versioning consequences as a function signature. These practices keep it predictable, each paired with the common habit it improves on.
Give errors types that callers can catch
Define a small hierarchy: one base error for your package and a few specific subclasses for conditions callers genuinely handle differently.
class ExampleLibError(Exception):
"""Base class for all errors raised by example_lib."""
class ConfigError(ExampleLibError):
pass
class RemoteUnavailable(ExampleLibError):
def __init__(self, url, status):
super().__init__(f"{url} returned {status}")
self.url = url
self.status = status
Instead of: raising a bare built-in exception for everything, which forces callers to catch too broadly or to inspect message text.
Expose stable codes or attributes, not message parsing
If callers need to branch on a reason, give them a field: a code string in JavaScript, an attribute in Python, a sentinel error value or typed error in Go that works with errors.Is and errors.As. Document these fields and keep them stable across minor releases.
Instead of: leaving callers to match on message text, which means improving a sentence becomes a breaking change.
Write messages for the person debugging
- Say what was expected and what was received: "expected a positive integer for timeout, got -5".
- Include the relevant identifier, such as a file path or key name, but never a secret or token.
- Suggest the likely fix when you know it.
Instead of: "invalid input", which sends users to your issue tracker.
Preserve the cause
When you wrap a lower-level failure, keep the original. Python's raise ... from err, JavaScript's new Error(msg, { cause }) and Go's fmt.Errorf("...: %w", err) all exist for this.
Instead of: catching an exception and raising a new one that hides where the problem began.
Do not swallow, print or exit
A library should report failures to its caller and let the application decide what to do. Logging an error and returning a default value hides bugs; calling process.exit or sys.exit from library code takes control away from the application entirely.
Instead of: deciding on the caller's behalf that a failure does not matter.
Test the failure paths
Error behaviour drifts silently because most test suites focus on the happy path. Add tests that assert the type, the code and the key attributes of each documented error, not the exact message. When one of those tests fails during a refactor, it is a prompt to ask whether the change is really a patch. Hypothetical Library B, for instance, could switch to a new HTTP client and start raising that client's exceptions instead of its own; a single assertion on the error type would catch it before release.
Version your errors like everything else
| Change | Usually |
|---|---|
| Clearer message text, same type and code | Patch |
| New error subclass of an existing type | Minor, since existing handlers still catch it |
| Raising a different, unrelated type for an existing failure | Major |
| Removing or renaming an error code | Major |
Record error changes in the changelog. See the API surface web read and what research says about breaking changes.