Returning validation error

func foo(w http.ResponseWriter, r *http.Request, status int, data interface{}){
	if err := encoder.Encode(w, r, data); err != nil {
		http.Error(//error here)
		}
}
			
foo(w, r, http.StatusBadRequest, fmt.Errorf("Invalid message")

this returns {} in an error condition instead of writing the actual error(Invalid message), what I am missing here. I want function to write the given error message.

Go PlayGround

I’m not sure if it’s relevant but you’re missing ) here in the end of line.

Just in case you aren’t already: make sure you’re calling return after calling http.Error else your program will continue.

that’s just copy pasta thing.

Also, it seems like the function doesn’t return anything?

it doesn’t have to as it is just wrapper to write response.

What is encoder.Encode? It doesn’t appear to be in the standard library and it’s hard to know how to help fix the code without knowing what the function is doing.

A playground link would be marvelous too, although I realize it’s not always that easy to yank something out of a large code base and get it running there.

I think your “//error here” comment is where the actual work should be done right? I would expect that line to be…

http.Error(w, err, 500)

Is that what your doing? If do, the response should have been written to the response writer’s “Write” method.

2 Likes

added the playground link above.

added the playground link with most of the code.

So I was stupid, I was passing an error such as errors.New(“error”), instead I need to pass errors.New(“error”).Error().

thanks Guys.

That just gives you the string “error” though, with a little bit of extra work (including an allocation?).

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.