Question
How can I return a custom error message along with an HTTP status code in a Go REST API?
Asked by: USER9281
88 Viewed
88 Answers
Answer (88)
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.