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"})
}
In Go this comes back as an error value, not a panic, and the bugstack SDK reports panics on its own. If it points to a bug in your code, report it where you handle it with bugstack.CaptureError(err); bugstack then works on it like any error the SDK reports.
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 error source
- 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
Set up once, and bugstack takes over the steps from reading the stack trace to proving the fix in an isolated sandbox and opening the pull request. Your CI runs on the pull request, and you set how much merges without you.
Step 1: Install the SDK
go get github.com/MasonBachmann7/bugstack-go
Step 2: Set it up
import bugstack "github.com/MasonBachmann7/bugstack-go"
endpoint := os.Getenv("BUGSTACK_ENDPOINT")
if endpoint == "" {
endpoint = "https://dashboard.bugstack.ai/api/ingest/sdk"
}
bugstack.Init(bugstack.Config{
APIKey: os.Getenv("BUGSTACK_API_KEY"),
Endpoint: endpoint,
})
defer bugstack.Flush()
// Report an error you handle yourself:
if err := chargeCard(order); err != nil {
bugstack.CaptureError(err)
return err
}
// Report (and recover) a panic in a goroutine you start:
go func() {
defer bugstack.Recover()
processJob(job)
}()
Set BUGSTACK_API_KEY to the key from your dashboard (it starts with bsk_). Then report it where you handle it with bugstack.CaptureError(err).
Step 3: Connect your repository
Sign in at dashboard.bugstack.ai with GitHub, start the 14-day trial, and install the bugstack GitHub App on the repository.
Then, each time the error is reported:
- Your report sends the error and its stack trace
- bugstack reads the files in the stack trace from your repository
- Specialist agents work out the cause and write a small change
- In an isolated sandbox, a test reproduces the error and fails on your current code; with the change it passes, and your other tests still pass
- The change arrives as a pull request with that test and its proof, and your CI runs on it
- On Review, the starting level, you merge it. On Autopilot it merges with green CI and its sandbox proof, checked again at merge.
You review a pull request instead of debugging.
You set how much merges without you.
Get started →Start with a 14-day trial: $50 of credit and a first security audit on us. Then Pro is $100 a month with $100 of usage credit every month. A card is required.
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
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.
In Go this comes back as an error value, not a panic, and the bugstack SDK reports panics on its own. If it points to a bug in your code, report it where you handle it with bugstack.CaptureError(err); bugstack then works on it like any error the SDK reports.
bugstack proves it before you see it. In an isolated copy of your repository, with the network cut, it writes a test that reproduces this error and fails on your current code; with the fix the test passes and the rest of your tests still pass. The pull request carries that test and its proof, your CI runs on it, and on Autopilot it merges only with that proof, checked again at merge.
A fix that does not turn the reproduction test green, or that breaks another test, never becomes a pull request. A fix that does is still a pull request, so your CI runs on it, and on Review, the starting level, a person merges it. Undoing a merged fix opens a revert pull request.
Stop fixing Go errors manually.
bugstack catches uncaught server errors, failed deploys and failing CI, works out the cause, and opens a pull request you control.