How do I translate validation errors in Go?

In Go, translating validation errors can be accomplished by using a custom error handling approach. Below is a simple example demonstrating how to define a validation error struct and translate it into user-friendly messages.

package main import ( "fmt" "errors" ) // ValidationError represents a custom error type type ValidationError struct { Field string Msg string } // Error implements the error interface for ValidationError func (ve *ValidationError) Error() string { return fmt.Sprintf("Field '%s': %s", ve.Field, ve.Msg) } // TranslateValidationError translates a validation error into a user-friendly message func TranslateValidationError(err error) string { if ve, ok := err.(*ValidationError); ok { switch ve.Field { case "username": return "Username must be at least 3 characters long." case "email": return "Please provide a valid email address." default: return "Invalid input for the field." } } return "Unknown error occurred." } func main() { // Simulating a validation error err := &ValidationError{Field: "username", Msg: "too short"} // Translating the error message friendlyMessage := TranslateValidationError(err) fmt.Println(friendlyMessage) // Outputs: Username must be at least 3 characters long. }

Go validation errors error handling in Go translate validation errors Go