CodexBloom - Programming Q&A Platform

Issue with Go's net/http and custom error handling during JSON marshalling

👀 Views: 183 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
go http json error-handling

I'm learning this framework and Quick question that's been bugging me - I'm optimizing some code but Could someone explain I'm working on a personal project and Quick question that's been bugging me - I'm encountering an issue while trying to send custom error responses in a Go HTTP server..... I'm using Go version 1.20 and I've implemented a simple middleware to handle errors uniformly. However, when I attempt to return a JSON response for errors, I get an unexpected behavior where the response body is not formatted correctly, and the status code doesn't match the error type. Here's my middleware code: ```go package main import ( "encoding/json" "net/http" ) type AppError struct { Message string `json:"message"` Code int `json:"code"` } func errorHandler(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { var appErr AppError switch e := err.(type) { case *AppError: appErr = *e default: appErr = AppError{Message: "Internal Server Error", Code: http.StatusInternalServerError} } w.Header().Set("Content-Type", "application/json") w.WriteHeader(appErr.Code) json.NewEncoder(w).Encode(appErr) } }() next.ServeHTTP(w, r) }) } func main() { http.Handle("/test", errorHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { panic(&AppError{Message: "Bad Request", Code: http.StatusBadRequest}) }))) http.ListenAndServe(":8080", nil) } ``` When I hit the `/test` endpoint, I expect to receive a JSON body like this: ```json { "message": "Bad Request", "code": 400 } ``` Instead, I just get an empty body with status 500, and no JSON output. I've checked that the custom error type is being triggered correctly, but it seems like the panic recovery is not behaving as I expected. I've also tried to log the error just before the response is sent, but the logging outputs the error correctly. Does anyone know why the JSON response isn't being sent properly? What could I be missing in the `errorHandler` function? Also, is there a better way to manage custom error responses in Go? This is part of a larger CLI tool I'm building. What am I doing wrong? Am I missing something obvious? Has anyone else encountered this? My development environment is Ubuntu 22.04. Cheers for any assistance! What am I doing wrong? I'm working on a microservice that needs to handle this. Any pointers in the right direction?