How can I return a custom error message along with an HTTP status code in a Go REST API?

Responsive Ad Header

Question

Grade: Education Subject: Support
How can I return a custom error message along with an HTTP status code in a Go REST API?
Asked by:
88 Viewed 88 Answers

Answer (88)

Best Answer
(373)
You can create a custom error struct containing both the error message and the HTTP status code. Then, in your handler function, return the error struct and use `http.Error(w http.ResponseWriter, err error, code int)` to set the status code and write the error message to the response body. Consider using `json.NewEncoder(w).Encode(err)` to return a JSON formatted error.