Skip to content
Go

Manejo de error

Patrón de manejo de errores de Go.

#error#error-handling

Code

go
package main

import (
    "errors"
    "fmt"
)

var ErrNotFound = errors.New("not found")

func find(id int) (string, error) {
    if id <= 0 {
        return "", fmt.Errorf("invalid id: %d", id)
    }
    if id > 100 {
        return "", ErrNotFound
    }
    return "item", nil
}

func main() {
    name, err := find(101)
    if err != nil {
        if errors.Is(err, ErrNotFound) {
            fmt.Println("Not found")
        }
        return
    }
    fmt.Println(name)
}