Skip to content

Instantly share code, notes, and snippets.

@farshidtz
Last active May 22, 2020 18:19
Show Gist options
  • Save farshidtz/70c942c424f1d166be74ca089235e141 to your computer and use it in GitHub Desktop.
Save farshidtz/70c942c424f1d166be74ca089235e141 to your computer and use it in GitHub Desktop.
Return error message along with a type. https://play.golang.org/p/9QsCFPXv_vV
package main
import (
"errors"
"fmt"
"strings"
)
// Simple errors
type NotFoundError struct{ s string }
func (e *NotFoundError) Error() string { return e.s }
type BadRequestError struct{ s string }
func (e *BadRequestError) Error() string { return e.s }
// Error as slice
type ConflictError struct{ errors []string }
func (e *ConflictError) Error() string { return strings.Join(e.errors, ", ") }
func (e *ConflictError) Errors() []string { return e.errors }
// A function returning different error types
func get(id string) error {
if id == "" {
return &BadRequestError{"id not given"}
} else if id == "3" {
return &NotFoundError{id + " is not found"}
} else if id == ":-)" {
return &ConflictError{[]string{"Char : is not allowed", "Char - is not allowed", "Char ) is not allowed"}}
} else {
return fmt.Errorf("function not implemented")
}
}
// Catching different error types
func main() {
// using type assertion
err := get("")
if err != nil {
if _, ok := err.(*NotFoundError); ok {
fmt.Printf("not found: %s\n", err)
} else {
fmt.Printf("some other error: %s\n", err)
}
}
// using type switch
err = get("3")
if err != nil {
switch e := err.(type) {
case *NotFoundError:
fmt.Printf("not found: %s\n", e)
case *BadRequestError:
fmt.Printf("bad request: %s\n", e)
case *ConflictError:
fmt.Printf("conflict: %s\n", e)
default:
fmt.Printf("some other error: %s\n", err)
}
}
// using error.As (Go >= 1.13)
err = get(":-)")
var e *ConflictError
if errors.As(err, &e) {
fmt.Printf("conflict (string): %s\n", e)
fmt.Printf("conflict (slice): %s\n", e.Errors())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment