0

Within an api I'm writing I have an error struct which marshals to json. When the api has an error it returns the struct and I set the http response code to be the appropriate value.

type PodsError struct {
    ErrorCode       int     `json:"error_code"`
    CallingFunction string  `json:"calling_function"`
    Message         string  `json:"error_message"`
}

type PodsErrorWrapper struct {
    Error   PodsError   `json:"error"`
}

Right now every time I write the struct I also write a header, but I don't like the amount of duplicate code I am seeing.

error := PodsError{http.StatusNotFound, "Calling Func", "Message"}
response.WriteHeader(error.ErrorCode)
response.WriteEntity(PodsErrorWrapper{error})

Is it possible to move the WriteHeader call to something that gets called whenever I pass the error to WriteEntity()? I figure there has to be a function I could implement for a PodsErrorWapper where I could just set the http status to be whatever the ErrorCode field is.

Edit: Sorry I forgot to mention, I am using the go-restful package (github.com/emicklei/go-restful)

4
  • what packages are you using? I don't know what is providing WriteEntity Commented May 1, 2015 at 19:08
  • whoops sorry I forgot to mention that, I am using github.com/emicklei/go-restful Commented May 1, 2015 at 19:27
  • Can you not do what you want with Filters alone? Commented May 1, 2015 at 19:54
  • 1
    This is a language feature called "functions" hth. Commented May 1, 2015 at 21:06

1 Answer 1

1

You can make your own function:

func writeEntity(r *restful.Response, value interface{}) error {
    // if value is an error
    if perr, ok := value.(PodsError); ok {
        r.WriteHeader(perr.ErrorCode)
        // reassign value so it gets wrapped: `{"error": value}`
        value = struct {
            Error PodsError `json:"error"`
        }{perr}
    }
    return r.WriteEntity(value)
}

Then just always call that instead of response.WriteEntity:

writeEntity(response, PodsError{http.StatusNotFound, "Calling Func", "Message"})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.