Repository: caddyserver/caddy (language: go)

Issue:
Caddy API returns a 500 when trying to POST/GET an `id` that does not exist
As you can see here:
![image](https://user-images.githubusercontent.com/25715982/152636777-2a291eb4-9c1a-4fd2-91cd-3225606bd1e1.png)

Caddy is returning a 500 when trying to get an ID that does not exist.  This should be a 404 instead of a 500. We are trying to make a k8 operator which has a CreateOrUpdate function for specific routes meaning we need to check if an ID exists. It would be nice to have  404 instead of a 500.


Discussion / hints:
Good idea. The `handleConfigID` handler could probably be modified to return `APIError` structs which specify the status code, rather than naked error values.

Fix patch:
diff --git a/admin.go b/admin.go
index 0a7b9330798..bd9c2aea7e4 100644
--- a/admin.go
+++ b/admin.go
@@ -905,10 +905,16 @@ func handleConfigID(w http.ResponseWriter, r *http.Request) error {
 
 	parts := strings.Split(idPath, "/")
 	if len(parts) < 3 || parts[2] == "" {
-		return fmt.Errorf("request path is missing object ID")
+		return APIError{
+			HTTPStatus: http.StatusBadRequest,
+			Err:        fmt.Errorf("request path is missing object ID"),
+		}
 	}
 	if parts[0] != "" || parts[1] != "id" {
-		return fmt.Errorf("malformed object path")
+		return APIError{
+			HTTPStatus: http.StatusBadRequest,
+			Err:        fmt.Errorf("malformed object path"),
+		}
 	}
 	id := parts[2]
 
@@ -917,7 +923,10 @@ func handleConfigID(w http.ResponseWriter, r *http.Request) error {
 	expanded, ok := rawCfgIndex[id]
 	defer currentCfgMu.RUnlock()
 	if !ok {
-		return fmt.Errorf("unknown object ID '%s'", id)
+		return APIError{
+			HTTPStatus: http.StatusNotFound,
+			Err:        fmt.Errorf("unknown object ID '%s'", id),
+		}
 	}
 
 	// piece the full URL path back together


Test patch: