Skip to content

Instantly share code, notes, and snippets.

@ejangi
Created July 3, 2024 01:51
Show Gist options
  • Save ejangi/cd13314065adc7a99bc1810177e7276a to your computer and use it in GitHub Desktop.
Save ejangi/cd13314065adc7a99bc1810177e7276a to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"github.com/pkg/errors"
)
// Custom Error Type
type InvalidInputError struct {
Field string
Message string
}
// Implement the error interface
func (e *InvalidInputError) Error() string {
return fmt.Sprintf("invalid input for field '%s': %s", e.Field, e.Message)
}
// Example Function
func calculateDiscount(price float64, discountPercent float64) (float64, error) {
if price < 0 {
return 0, errors.Wrap(&InvalidInputError{Field: "price", Message: "must be non-negative"}, "calculateDiscount failed")
}
if discountPercent < 0 || discountPercent > 100 {
return 0, errors.Wrap(&InvalidInputError{Field: "discountPercent", Message: "must be between 0 and 100"}, "calculateDiscount failed")
}
discountAmount := price * discountPercent / 100
return price - discountAmount, nil
}
func main() {
discountedPrice, err := calculateDiscount(-10, 20)
if err != nil {
fmt.Printf("Error: %+v\n", err) // Print the error with stack trace
if inputErr, ok := errors.Cause(err).(*InvalidInputError); ok {
fmt.Println("Invalid input:", inputErr.Field, inputErr.Message) // Access specific error details
}
return
}
fmt.Println("Discounted price:", discountedPrice)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment