Skip to content

Commit 6ff8ccf

Browse files
authored
return 404 when no matching route is found (#1067)
* return 404 when a matching route is not found * update other middleware and tests
1 parent 0b34a3f commit 6ff8ccf

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

oapi_validate.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,18 @@ func OapiRequestValidatorWithOptions(swagger *openapi3.T, options *Options) gin.
8888
return func(c *gin.Context) {
8989
err := ValidateRequestFromContext(c, router, options)
9090
if err != nil {
91-
if options != nil && options.ErrorHandler != nil {
92-
options.ErrorHandler(c, err.Error(), http.StatusBadRequest)
91+
// using errors.Is did not work
92+
if options != nil && options.ErrorHandler != nil && err.Error() == routers.ErrPathNotFound.Error() {
93+
options.ErrorHandler(c, err.Error(), http.StatusNotFound)
9394
// in case the handler didn't internally call Abort, stop the chain
9495
c.Abort()
96+
} else if options != nil && options.ErrorHandler != nil {
97+
options.ErrorHandler(c, err.Error(), http.StatusBadRequest)
98+
// in case the handler didn't internally call Abort, stop the chain
99+
c.Abort()
100+
} else if err.Error() == routers.ErrPathNotFound.Error() {
101+
// note: i am not sure if this is the best way to handle this
102+
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": err.Error()})
95103
} else {
96104
// note: i am not sure if this is the best way to handle this
97105
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})

oapi_validate_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,10 +101,10 @@ func TestOapiRequestValidator(t *testing.T) {
101101
g.GET("/resource", func(c *gin.Context) {
102102
called = true
103103
})
104-
// Let's send the request to the wrong server, this should fail validation
104+
// Let's send the request to the wrong server, this should return 404
105105
{
106106
rec := doGet(t, g, "http://not.deepmap.ai/resource")
107-
assert.Equal(t, http.StatusBadRequest, rec.Code)
107+
assert.Equal(t, http.StatusNotFound, rec.Code)
108108
assert.False(t, called, "Handler should not have been called")
109109
}
110110

0 commit comments

Comments
 (0)