Error and Exception Handling
Last updated
Last updated
This page contains recommendations for handling errors and exceptions.
Handle each error and exception using a common handling component.
Override the default error page for unhandled errors and exceptions.
Error and exception handling complies with the fail-secure
security design principle:
An application is returned to the most secure state when an error or exception occurs.
An application denies access by default when an error or exception occurs.
Error messages are not verbose in nature:
Do not pass sensitive data in error messages see the Sensitive Data Management page.
Do not include a stack trace in error messages and HTTP responses.
Do not pass server configuration information (name, version, etc.) in error messages.
Do not ignore errors in security-related components like crypto modules.
Log errors according to the Logging and Monitoring page.
In Go, you have to be aware of uncaught panics and handle them to prevent an application from crashing. You can omit the goroutine stack traces entirely by setting the GOTRACEBACK
environment variable to none
. In this case, you will only receive a panic message. See https://pkg.go.dev/runtime#hdr-Environment_Variables
Additionally, you can override a panic recovery and implement custom logic.
Recover only works when called from the same goroutine as the panic is called in, see https://go.dev/ref/spec#Handling_panics
Use the following approaches to implement panic handling:
Use the defer
statement to handle panics, see https://go.dev/blog/defer-panic-and-recover
Implement a middleware to handle panics.
Remember that some packages can handle panics out of the box, net/http as an example.