diff --git a/internal/dev_server/api/error_handlers.go b/internal/dev_server/api/error_handlers.go new file mode 100644 index 00000000..d36bfcdb --- /dev/null +++ b/internal/dev_server/api/error_handlers.go @@ -0,0 +1,39 @@ +package api + +import ( + "encoding/json" + "log" + "net/http" +) + +type errorHandler struct { + code string + statusCode int +} + +func (eh errorHandler) HandleError(w http.ResponseWriter, r *http.Request, err error) { + log.Printf("Error while handling request: %+v", err) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(eh.statusCode) + err = json.NewEncoder(w).Encode(ErrorResponseJSONResponse{ + Code: eh.code, + Message: err.Error(), + }) + if err != nil { + log.Printf("Error while writing error response: %+v", err) + } +} + +var RequestErrorHandler = errorHandler{ + // HACK: This is really just repeating the status code. + // It'd be nice to make these be codes that are meaningful to the user. + code: "bad_request", + statusCode: http.StatusBadRequest, +}.HandleError + +var ResponseErrorHandler = errorHandler{ + // HACK: This is really just repeating the status code. + // It'd be nice to make these be codes that are meaningful to the user. + code: "internal_server_error", + statusCode: http.StatusInternalServerError, +}.HandleError diff --git a/internal/dev_server/dev_server.go b/internal/dev_server/dev_server.go index 223689e0..ae820f5b 100644 --- a/internal/dev_server/dev_server.go +++ b/internal/dev_server/dev_server.go @@ -50,8 +50,8 @@ func (c LDClient) RunServer(ctx context.Context, serverParams ServerParams) { } ss := api.NewStrictServer() apiServer := api.NewStrictHandlerWithOptions(ss, nil, api.StrictHTTPServerOptions{ - RequestErrorHandlerFunc: RequestErrorHandler, - ResponseErrorHandlerFunc: ResponseErrorHandler, + RequestErrorHandlerFunc: api.RequestErrorHandler, + ResponseErrorHandlerFunc: api.ResponseErrorHandler, }) r := mux.NewRouter() r.Use(adapters.Middleware(*ldClient, serverParams.DevStreamURI)) @@ -75,15 +75,6 @@ func (c LDClient) RunServer(ctx context.Context, serverParams ServerParams) { log.Fatal(server.ListenAndServe()) } -func ResponseErrorHandler(w http.ResponseWriter, r *http.Request, err error) { - log.Printf("Error while serving response: %+v", err) - http.Error(w, err.Error(), http.StatusInternalServerError) -} -func RequestErrorHandler(w http.ResponseWriter, r *http.Request, err error) { - log.Printf("Error while serving request: %+v", err) - http.Error(w, err.Error(), http.StatusBadRequest) -} - func getDBPath() string { dbFilePath, err := xdg.StateFile("ldcli/dev_server.db") if err != nil {