1
0
mirror of https://github.com/alice-lg/alice-lg.git synced 2024-05-11 05:55:03 +00:00
alice-lg-alice-lg/pkg/backend/api_errors.go

81 lines
1.9 KiB
Go
Raw Normal View History

2021-03-22 16:25:47 +01:00
package backend
2018-08-05 18:25:59 +02:00
// 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 (
2019-01-11 20:06:03 +01:00
"net/http"
2018-08-05 18:25:59 +02:00
"net/url"
"strings"
2021-03-22 16:50:08 +01:00
"github.com/alice-lg/alice-lg/pkg/api"
2018-08-05 18:25:59 +02:00
)
2021-03-22 16:50:08 +01:00
// ResourceNotFoundError is a 404 error
2019-01-11 20:06:03 +01:00
type ResourceNotFoundError struct{}
2021-03-22 16:50:08 +01:00
// Error implements the error interface and returns
// the error message
func (err *ResourceNotFoundError) Error() string {
2019-01-11 20:06:03 +01:00
return "resource not found"
}
2021-03-22 16:50:08 +01:00
// Variables
var (
SOURCE_NOT_FOUND_ERROR = &ResourceNotFoundError{}
)
2019-01-11 20:06:03 +01:00
2021-03-22 16:50:08 +01:00
// Error Constants
2018-08-05 18:25:59 +02:00
const (
GENERIC_ERROR_TAG = "GENERIC_ERROR"
CONNECTION_REFUSED_TAG = "CONNECTION_REFUSED"
CONNECTION_TIMEOUT_TAG = "CONNECTION_TIMEOUT"
2019-01-11 20:06:03 +01:00
RESOURCE_NOT_FOUND_TAG = "NOT_FOUND"
2018-08-05 18:25:59 +02:00
)
const (
GENERIC_ERROR_CODE = 42
CONNECTION_REFUSED_CODE = 100
CONNECTION_TIMEOUT_CODE = 101
2019-01-11 20:06:03 +01:00
RESOURCE_NOT_FOUND_CODE = 404
2018-08-05 18:25:59 +02:00
)
2019-01-11 20:06:03 +01:00
const (
ERROR_STATUS = http.StatusInternalServerError
RESOURCE_NOT_FOUND_STATUS = http.StatusNotFound
)
2021-03-22 16:50:08 +01:00
// Handle an error and create a error API response
2019-01-11 20:06:03 +01:00
func apiErrorResponse(routeserverId string, err error) (api.ErrorResponse, int) {
2018-08-05 18:25:59 +02:00
code := GENERIC_ERROR_CODE
message := err.Error()
tag := GENERIC_ERROR_TAG
2019-01-11 20:06:03 +01:00
status := ERROR_STATUS
2018-08-05 18:25:59 +02:00
switch e := err.(type) {
2019-01-11 20:06:03 +01:00
case *ResourceNotFoundError:
tag = RESOURCE_NOT_FOUND_TAG
code = RESOURCE_NOT_FOUND_CODE
status = RESOURCE_NOT_FOUND_STATUS
2018-08-05 18:25:59 +02:00
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,
2019-01-11 20:06:03 +01:00
}, status
2018-08-05 18:25:59 +02:00
}