Always handle errors comprehensively by checking return values, implementing proper error propagation, and ensuring resources are cleaned up. Errors that are ignored or improperly handled can lead to resource leaks, unexpected behavior, or application crashes.
Always handle errors comprehensively by checking return values, implementing proper error propagation, and ensuring resources are cleaned up. Errors that are ignored or improperly handled can lead to resource leaks, unexpected behavior, or application crashes.
Follow these principles:
_
) unless you have explicitly determined the error can be safely ignored.// Bad
cfg.BandwidthLimit, _ = NewBandwidthQuantity(pMsg.BandwidthLimit) // Ignores error, creating empty bandwidth limit
// Good
cfg.BandwidthLimit, err = NewBandwidthQuantity(pMsg.BandwidthLimit)
if err != nil {
// Handle appropriately: set default, log warning, or return error
xl.Warnf("Invalid bandwidth limit %q: %v", pMsg.BandwidthLimit, err)
}
// Bad
func (c *Controller) RegisterClientRoute(ctx context.Context, name string, routes []net.IPNet, conn io.ReadWriteCloser) {
// No way to signal failure to caller
}
// Good
func (c *Controller) RegisterClientRoute(ctx context.Context, name string, routes []net.IPNet, conn io.ReadWriteCloser) error {
// Implementation
return err // Return any failure
}
// Bad
if err := svr.RegisterWorkConn(conn, m); err != nil {
// Error logged but connection left open
}
// Good
if err := svr.RegisterWorkConn(conn, m); err != nil {
conn.Close() // Clean up resources
}
// Good
if onClose != nil {
func() {
defer func() {
if r := recover(); r != nil {
xl.Warnf("onClose callback panicked: %v", r)
}
}()
onClose()
}()
}
Complete error handling is essential for building reliable and maintainable software.
Enter the URL of a public GitHub repository