Sobes.tech
Senior

Why does the API handler always return status 500? What's wrong with it?

sobes.tech AI

Answer from AI

Returning a 500 Internal Server Error status everywhere in the API handler is bad practice because this status indicates that an unexpected error occurred on the server.

Problems with this approach:

  • Lack of precise diagnostics: The client does not understand what exactly went wrong — whether it was a validation error, missing data, or a server issue.
  • Violation of REST standards: HTTP has many status codes that help the client handle responses correctly (e.g., 400 for client errors, 404 for not found resources, 401 for unauthorized requests).
  • Debugging difficulties: If you always return 500, it is hard to quickly identify the cause of the error.

The correct approach is to return different status codes depending on the situation:

  • 200 OK — successful request.
  • 400 Bad Request — error in the request (e.g., invalid parameters).
  • 401 Unauthorized — if the user is not authorized.
  • 404 Not Found — if the resource is not found.
  • 500 Internal Server Error — for unexpected server errors.

Example in Go:

func handler(w http.ResponseWriter, r *http.Request) {
    id := r.URL.Query().Get("id")
    if id == "" {
        http.Error(w, "missing id", http.StatusBadRequest)
        return
    }

    data, err := getDataByID(id)
    if err == ErrNotFound {
        http.Error(w, "not found", http.StatusNotFound)
        return
    } else if err != nil {
        http.Error(w, "internal error", http.StatusInternalServerError)
        return
    }

    w.WriteHeader(http.StatusOK)
    w.Write(data)
}

Thus, proper use of status codes improves client interaction and simplifies API maintenance.