Error Handling in Go
Error handling in Go is simple and idiomatic, using explicit error checks. Go's clarity makes managing errors straightforward. Here's an example with custom error types and error wrapping.
Example: Custom Error Types and Error Wrapping
package main
import (
"errors"
"fmt"
)
type CustomError struct {
Code int
Msg string
}
func (e *CustomError) Error() string {
return fmt.Sprintf("Code: %d, Msg: %s", e.Code, e.Msg)
}
func riskyOperation() error {
return &CustomError{Code: 404, Msg: "Resource not found"}
}
func main() {
err := riskyOperation()
if err != nil {
fmt.Println("Error occurred:", err)
var customErr *CustomError
if errors.As(err, &customErr) {
fmt.Printf("Custom Error - Code: %d, Msg: %s\n", customErr.Code, customErr.Msg)
}
}
}
Explanation
Custom Error Type: Define a
CustomError
struct implementing theError
method.Risky Operation: The
riskyOperation
function returns aCustomError
.Error Handling: In
main
, check for errors and useerrors.As
to handle the custom error type.
By following these patterns, you can create clear and maintainable error handling in your Go applications.