G
Tratamento de Erros
Go Syntax Guide
Gerenciar erros com múltiplos valores de retorno e o tipo error
Tratamento de Erros
Gerenciar erros com múltiplos valores de retorno e o tipo error
Go tratamento de erros (go)
package main
import (
"errors"
"fmt"
"strconv"
)
// Custom error types
type ValidationError struct {
Field string
Message string
}
func (e ValidationError) Error() string {
return fmt.Sprintf("validation error on field '%s': %s", e.Field, e.Message)
}
type NetworkError struct {
Code int
Message string
}
func (e NetworkError) Error() string {
return fmt.Sprintf("network error %d: %s", e.Code, e.Message)
}
// Function that returns an error
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
// Function with custom error
func validateAge(age int) error {
if age < 0 {
return ValidationError{Field: "age", Message: "cannot be negative"}
}
if age > 150 {
return ValidationError{Field: "age", Message: "seems unrealistic"}
}
return nil
}
// Function that can return different error types
func processUserData(data map[string]interface{}) error {
// Simulate network call
if data["network_error"] != nil {
return NetworkError{Code: 500, Message: "server error"}
}
if name, ok := data["name"].(string); !ok {
return ValidationError{Field: "name", Message: "must be string"}
} else if name == "" {
return ValidationError{Field: "name", Message: "cannot be empty"}
}
if age, ok := data["age"].(float64); !ok {
return ValidationError{Field: "age", Message: "must be number"}
} else {
return validateAge(int(age))
}
}
// Panic and recover
func riskyOperation() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
// Simulate a panic
panic("something went wrong!")
}
// Error wrapping (Go 1.13+)
func processFile(filename string) error {
data, err := readFile(filename)
if err != nil {
return fmt.Errorf("failed to process file %s: %w", filename, err)
}
return processData(data)
}
// Mock functions for demonstration
func readFile(filename string) ([]byte, error) {
if filename == "" {
return nil, errors.New("filename cannot be empty")
}
return []byte("file content"), nil
}
func processData(data []byte) error {
if len(data) == 0 {
return errors.New("data cannot be empty")
}
return nil
}
func main() {
// Basic error handling
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("Result: %.2f\n", result)
}
// Custom errors
if err := validateAge(-5); err != nil {
fmt.Println("Validation error:", err)
// Type assertion to access custom error fields
if valErr, ok := err.(ValidationError); ok {
fmt.Printf("Field: %s, Message: %s\n", valErr.Field, valErr.Message)
}
}
// Process user data
userData := map[string]interface{}{
"name": "John",
"age": 25,
}
if err := processUserData(userData); err != nil {
fmt.Println("User data error:", err)
}
// Panic and recover
fmt.Println("About to run risky operation...")
riskyOperation()
fmt.Println("Program continues after recovery")
// Error wrapping
if err := processFile(""); err != nil {
fmt.Println("Wrapped error:", err)
// Check if error wraps another error
if wrappedErr := errors.Unwrap(err); wrappedErr != nil {
fmt.Println("Original error:", wrappedErr)
}
}
}
Explanation
Go lida com erros retornando-os como o último valor de retorno de uma função. O chamador então verifica explicitamente se o erro é nil (sem erro) ou não.
Common Use Cases
- Validar entradas de função
- Lidar com falhas de E/S de arquivo
- Gerenciar problemas de comunicação de rede
Related Go Syntax
Master Tratamento de Erros in Go
Understanding Tratamento de Erros is fundamental to writing clean and efficient Go code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.
Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using Tratamento de Erros effectively in your Go projects.
Key Takeaways
- Validar entradas de função
- Lidar com falhas de E/S de arquivo
- Gerenciar problemas de comunicação de rede