From 058ce19858d1e97a433f9835bcf8471ac5c92140 Mon Sep 17 00:00:00 2001 From: Matthias Hannig Date: Sun, 5 Aug 2018 18:25:59 +0200 Subject: [PATCH] improved error handling --- backend/api.go | 9 ++++++-- backend/api/response.go | 5 +++- backend/api_errors.go | 51 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 3 deletions(-) create mode 100644 backend/api_errors.go diff --git a/backend/api.go b/backend/api.go index f3bc13c..efb03a6 100644 --- a/backend/api.go +++ b/backend/api.go @@ -45,9 +45,14 @@ func endpoint(wrapped apiEndpoint) httprouter.Handle { // Get result from handler result, err := wrapped(req, params) if err != nil { - result = api.ErrorResponse{ - Error: err.Error(), + // Get affected rs id + rsId, paramErr := validateSourceId(params.ByName("id")) + if paramErr != nil { + rsId = -1 } + + // Make error response + result = apiErrorResponse(rsId, err) payload, _ := json.Marshal(result) http.Error(res, string(payload), http.StatusInternalServerError) return diff --git a/backend/api/response.go b/backend/api/response.go index 3b553ec..eea8a45 100644 --- a/backend/api/response.go +++ b/backend/api/response.go @@ -12,7 +12,10 @@ type Details map[string]interface{} // Error Handling type ErrorResponse struct { - Error string `json:"error"` + Message string `json:"message"` + Code int `json:"code"` + Tag string `json:"tag"` + RouteserverId int `json:"routeserver_id"` } // Cache aware api response diff --git a/backend/api_errors.go b/backend/api_errors.go new file mode 100644 index 0000000..5204451 --- /dev/null +++ b/backend/api_errors.go @@ -0,0 +1,51 @@ +package main + +// Improve error handling +// Create api.ErrorResponses based on errors returned from server. +// Strip out potentially sensitive information, eg. connection errors +// to internal IP addresses. + +import ( + "net/url" + "strings" + + "github.com/alice-lg/alice-lg/backend/api" +) + +const ( + GENERIC_ERROR_TAG = "GENERIC_ERROR" + CONNECTION_REFUSED_TAG = "CONNECTION_REFUSED" + CONNECTION_TIMEOUT_TAG = "CONNECTION_TIMEOUT" +) + +const ( + GENERIC_ERROR_CODE = 42 + CONNECTION_REFUSED_CODE = 100 + CONNECTION_TIMEOUT_CODE = 101 +) + +func apiErrorResponse(routeserverId int, err error) api.ErrorResponse { + code := GENERIC_ERROR_CODE + message := err.Error() + tag := GENERIC_ERROR_TAG + + switch e := err.(type) { + case *url.Error: + if strings.Contains(message, "connection refused") { + tag = CONNECTION_REFUSED_TAG + code = CONNECTION_REFUSED_CODE + message = "Connection refused while dialing the API" + } else if e.Timeout() { + tag = CONNECTION_TIMEOUT_TAG + code = CONNECTION_TIMEOUT_CODE + message = "Connection timed out when connecting to the backend API" + } + } + + return api.ErrorResponse{ + Code: code, + Tag: tag, + Message: message, + RouteserverId: routeserverId, + } +}