HTTP JSON Error Responses in Go

{
"error": {
"type": "validation_failed",
"message": "Username is a required field"
}
}
tx, err := usr.Create(ctx, env)
if err != nil {
return errorHandler.HTTPErr{
Code: http.StatusBadRequest,
Type: "validation_failed",
Err: err,
}
}
func newUser(ctx context.Context, env *env.Env, cur *createUserRequest) (*appUser.User, error) {// declare a new instance of appUser.User
usr := new(appUser.User)
// initialize an errorHandler with the default Code and Type for
// service validations (Err is set to nil as it will be set later)
e := errorHandler.HTTPErr{
Code: http.StatusBadRequest,
Type: "validation_error",
Err: nil,
}
// for each field you can go through whatever validations you wish
// and use the SetErr method of the HTTPErr struct to add the proper
// error text
switch {
// Username is required
case cur.Username == "":
e.SetErr("Username is a required field")
return nil, e
// Username cannot be blah...
case cur.Username == "blah":
e.SetErr("Username cannot be blah")
return nil, e
// If we get through the switch, set the field
default:
usr.Username = cur.Username
}
.....

--

--

Go enthusiast; Loyalty/CRM Technology Leader; Drummer; Vinyl geek; Husband/Dad

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dan Gillis

Dan Gillis

Go enthusiast; Loyalty/CRM Technology Leader; Drummer; Vinyl geek; Husband/Dad