Skip to content

Cannot validate incorrect types #202

@threesquared

Description

@threesquared

Describe the bug

When validating an input with an incorrect type we get an failed to decode json: json: cannot unmarshall... error instead of a validation failed error with a context object pointing to the issue. This is because the un-marshalling fails before the validator is even run.

To Reproduce

package main

import (
	"bytes"
	"context"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/swaggest/rest/web"
	"github.com/swaggest/usecase"
)

func TestFoo(t *testing.T) {
	type TestInput struct {
		TestString string `json:"testString" default:"valid" required:"true" minLength:"5" maxLength:"10" pattern:"^[a-z]+$"`
	}

	s := web.DefaultService()

	s.Post("/foo", usecase.NewInteractor(func(ctx context.Context, input TestInput, output *string) error {
		*output = input.TestString

		return nil
	}))

	req, err := http.NewRequest(http.MethodPost, "/foo", bytes.NewReader([]byte(`{"testString":77}`)))
	require.NoError(t, err)
	req.Header.Set("Content-Type", "application/json")
	rw := httptest.NewRecorder()

	s.ServeHTTP(rw, req)
	assert.Contains(t, rw.Body.String(), "validation failed")
	assert.Equal(t, http.StatusBadRequest, rw.Code)
}

Expected behavior

I would expect a type mismatch issue to be reported in the same way as any other validation error to the end user

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions