Fix BindingError: code=400, message=Unmarshal type error: expected=int, got=string, field=age, offset=25 in Echo
This error occurs when Echo's Bind method encounters a JSON field whose type does not match the struct definition, such as sending a string where an int is expected. Fix it by validating the bind error, returning structured 400 responses with field-level details, and using a custom validator for business rule checks.
Reading the Stack Trace
Here's what each line means:
- main.CreateUser({0x1029e4f80, 0x14000226000}) /app/handlers/user.go:18 +0x1a4: The CreateUser handler at line 18 calls Bind which fails because the JSON payload has a type mismatch for the age field.
- encoding/json.(*Decoder).Decode(0x14000196040, {0x102850ea0, 0x14000196060}): Go's JSON decoder encounters a string value for a field declared as int, producing an UnmarshalTypeError.
- github.com/labstack/echo/v4.(*Echo).ServeHTTP(0x14000128680, {0x1029e4f80, 0x140001c40e0}, 0x140002b4000): Echo's HTTP handler dispatches the request to the CreateUser handler through the middleware chain.
Common Causes
1. Type mismatch between JSON and struct
The client sends a string for a field declared as int in the Go struct, causing a JSON unmarshal type error.
type CreateUserRequest struct {
Name string `json:"name"`
Age int `json:"age"`
}
func CreateUser(c echo.Context) error {
var req CreateUserRequest
c.Bind(&req) // ignores error
return c.JSON(200, req)
}
2. Bind error not handled
The error from Bind is ignored, causing the handler to proceed with zero-value fields.
func CreateUser(c echo.Context) error {
var req CreateUserRequest
c.Bind(&req) // error silently swallowed
// req.Age is 0, req.Name is empty
db.Create(&User{Name: req.Name, Age: req.Age})
return c.JSON(200, gin.H{"status": "created"})
}
3. No validation beyond type checking
Bind only checks types. Business rules like 'age must be > 0' are not enforced without a validator.
func CreateUser(c echo.Context) error {
var req CreateUserRequest
if err := c.Bind(&req); err != nil {
return err
}
// Age = 0 or negative passes Bind but is invalid
db.Create(&User{Name: req.Name, Age: req.Age})
return c.JSON(200, gin.H{"status": "ok"})
}
The Fix
Handle the Bind error explicitly, register a custom validator on the Echo instance, and validate the struct after binding. Return structured 400 responses with details about which fields failed validation.
func CreateUser(c echo.Context) error {
var req CreateUserRequest
c.Bind(&req)
db.Create(&User{Name: req.Name, Age: req.Age})
return c.JSON(200, map[string]string{"status": "created"})
}
type CustomValidator struct {
validator *validator.Validate
}
func (cv *CustomValidator) Validate(i interface{}) error {
return cv.validator.Struct(i)
}
type CreateUserRequest struct {
Name string `json:"name" validate:"required,min=2"`
Age int `json:"age" validate:"required,gte=1,lte=150"`
}
func CreateUser(c echo.Context) error {
var req CreateUserRequest
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body"})
}
if err := c.Validate(&req); err != nil {
return c.JSON(http.StatusBadRequest, map[string]interface{}{
"error": "validation_failed",
"details": err.Error(),
})
}
db.Create(&User{Name: req.Name, Age: req.Age})
return c.JSON(http.StatusCreated, map[string]string{"status": "created"})
}
Testing the Fix
package handlers_test
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)
func TestCreateUser_TypeMismatch(t *testing.T) {
e := echo.New()
e.Validator = &CustomValidator{validator: validator.New()}
body := `{"name": "Alice", "age": "not-a-number"}`
req := httptest.NewRequest(http.MethodPost, "/api/users", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
err := CreateUser(c)
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, rec.Code)
}
func TestCreateUser_ValidPayload(t *testing.T) {
e := echo.New()
e.Validator = &CustomValidator{validator: validator.New()}
body := `{"name": "Alice", "age": 30}`
req := httptest.NewRequest(http.MethodPost, "/api/users", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
err := CreateUser(c)
assert.NoError(t, err)
assert.Equal(t, http.StatusCreated, rec.Code)
}
Run your tests:
go test ./handlers/... -v
Pushing Through CI/CD
git checkout -b fix/echo-binding-error,git add handlers/user.go handlers/user_test.go,git commit -m "fix: handle Bind errors and add struct validation in Echo handler",git push origin fix/echo-binding-error
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.22'
- run: go mod download
- run: go vet ./...
- run: go test ./... -race -coverprofile=coverage.out
- run: go build ./...
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
go get github.com/bugstack/sdk
Step 2: Initialize
import "github.com/bugstack/sdk"
func init() {
bugstack.Init(os.Getenv("BUGSTACK_API_KEY"))
}
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run go test ./... locally to confirm the fix passes.
- Open a pull request with the binding and validation changes.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify the deployment in staging before promoting to production.
Frequently Asked Questions
BugStack runs the fix through your existing test suite, generates tests for malformed payloads and type mismatches, and validates that all endpoints return correct status codes before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
Echo's Bind auto-detects the content type and binds from JSON, form, or query params. Gin's ShouldBindJSON is explicit about JSON only. Both return errors for type mismatches.
Yes. Echo does not include a validator. You must implement the echo.Validator interface and assign it to e.Validator. The go-playground/validator package is the standard choice.