Home > Backend Development > Golang > How to Customize Error Messages from Gin's Struct Tag Validation?

How to Customize Error Messages from Gin's Struct Tag Validation?

Susan Sarandon
Release: 2024-12-15 05:42:10
Original
516 people have browsed it

How to Customize Error Messages from Gin's Struct Tag Validation?

Customizing Error Messages from Struct Tag Validation

In Gin, struct tag validation is used to ensure data integrity before database insertion. The default error returned is verbose and uninformative for the user. This article describes how to customize the error message to provide a more meaningful response.

Gin utilizes the go-playground/validator/v10 package for validation. Errors are returned as validator.ValidationErrors. To customize the message, use the standard errors package to unwrap the error and access the validator.FieldError fields.

Create an error model (e.g., ApiError) to define the structure of your custom error message. For instance:

type ApiError struct {
    Field string
    Msg   string
}
Copy after login

In your handler, handle the error as follows:

var u User
err := c.BindQuery(&u);
if err != nil {
    var ve validator.ValidationErrors
    if errors.As(err, &ve) {
        out := make([]ApiError, len(ve))
        for i, fe := range ve {
            out[i] = ApiError{fe.Field(), msgForTag(fe.Tag())}
        }
        c.JSON(http.StatusBadRequest, gin.H{"errors": out})
    }
    return
}
Copy after login

Finally, define a helper function to map validation tags to custom messages:

func msgForTag(tag string) string {
    switch tag {
    case "required":
        return "This field is required"
    case "email":
        return "Invalid email"
    }
    return ""
}
Copy after login

Using this approach, error messages will be customized with the field name and a tailored message based on the validation tag.

The above is the detailed content of How to Customize Error Messages from Gin's Struct Tag Validation?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template