How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Echo · Go

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

2024/03/15 14:22:31 echo: POST /api/users -> main.CreateUser | 400 | 1.204ms | 127.0.0.1 goroutine 34 [running]: runtime/debug.Stack() /usr/local/go/src/runtime/debug/stack.go:24 +0x5e main.CreateUser({0x1029e4f80, 0x14000226000}) /app/handlers/user.go:18 +0x1a4 github.com/labstack/echo/v4.(*Echo).add(0x14000128680, {0x1028f0f20, 0x4}, {0x1028f1e60, 0xb}, {0x14000116420, 0x1, 0x1}) /go/pkg/mod/github.com/labstack/echo/v4@v4.11.4/echo.go:542 +0x2d8 github.com/labstack/echo/v4.(*Echo).ServeHTTP(0x14000128680, {0x1029e4f80, 0x140001c40e0}, 0x140002b4000) /go/pkg/mod/github.com/labstack/echo/v4@v4.11.4/echo.go:669 +0x1a0 encoding/json.(*Decoder).Decode(0x14000196040, {0x102850ea0, 0x14000196060}) /usr/local/go/src/encoding/json/stream.go:73 +0x134

Here's what each line means:

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.

Before (broken)
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"})
}
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run go test ./... locally to confirm the fix passes.
  2. Open a pull request with the binding and validation changes.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. 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.