oapi-codegen icon indicating copy to clipboard operation
oapi-codegen copied to clipboard

gin server append error with c.Error() instead of dumping it with c.JSON()

Open chase-isabelle-roostify opened this issue 3 years ago • 4 comments

When the gin server code is generated, it provides a wrapper for the service interface. This wrapper does some request validation logic; however, when it encounters an error, it dumps it to the response payload...

// FindPetById operation middleware
func (siw *ServerInterfaceWrapper) FindPetById(c *gin.Context) {
	...
	err = runtime.BindStyledParameter("simple", false, "id", c.Param("id"), &id)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"msg": fmt.Sprintf("Invalid format for parameter id: %s", err)})
		return
	}
	...
}

What is expected is...

// FindPetById operation middleware
func (siw *ServerInterfaceWrapper) FindPetById(c *gin.Context) {
	...
	err = runtime.BindStyledParameter("simple", false, "id", c.Param("id"), &id)
	if err != nil {
		c.Error(err)
		return
	}
	...
}

...this way a middleware can handle the error. Is there a way to either:

  1. Generate the wrapper so it behaves as ☝️ ?
  2. Omit the wrapper and implement the validation myself?

This is the command I'm using to generate the gin server:

oapi-codegen -generate gin,types,spec -package api api/openapi/api.yaml > internal/api/openapi/api.go

chase-isabelle-roostify avatar May 20 '22 15:05 chase-isabelle-roostify

I would like to submit a PR for this, but it appears I don't have rights:

$ git push origin gin-error-handler-option
ERROR: Permission to deepmap/oapi-codegen.git denied to chase-isabelle-roostify.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists

Could someone grant me rights?

chaseisabelle avatar May 20 '22 19:05 chaseisabelle

You have to send a pull request from your own branch in your own repo, and I will pull the change.

Please see https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request

You don't need any push access to our repo to do this, you must push to your own fork.

deepmap-marcinr avatar May 20 '22 23:05 deepmap-marcinr

@deepmap-marcinr thank you! i've added my pr, please have a look when you have a moment. https://github.com/deepmap/oapi-codegen/pull/587

chaseisabelle avatar May 21 '22 04:05 chaseisabelle

I managed to mitigate this issue using custom templates: https://github.com/deepmap/oapi-codegen#making-changes-to-code-generation

chaseisabelle avatar Jul 07 '22 03:07 chaseisabelle