It’s OK to Panic in Go
Go’s error handling is very explicit. It can also be very verbose compared to other languages. I want to talk about how we can minimize the need for explicit error handling by separating what are expected and unexpected errors.
Expected Errors
An expected error is generally something you can test/check/verify ahead of time or that would not have a detrimental effect on the system. Some examples of expected errors are:
- Validating an email address from an input.
- Verifying that a user has access to a certain part of the system.
- Retry on a known flaky or slow API endpoint.
Expected errors should always return an error. This lets the caller decide what to do in this case. It may want to bubble the error up, or it may choose to bail out of the current operation.
This is where explicit error handing code actually shines (compared to implicit error handling such as exceptions) because you have to decide what to do in that case.
Unexpected Errors
An unexpected error is something that would put the system into an unreasonable state or recovering is not possible without explicit handling of that case.