mirror of
https://github.com/absmach/magistrala.git
synced 2026-06-23 04:10:28 +00:00
NOISSUE - Handle callout error (#3039)
Signed-off-by: Arvindh <arvindh91@gmail.com>
This commit is contained in:
+9
-1
@@ -166,12 +166,20 @@ func EncodeResponse(_ context.Context, w http.ResponseWriter, response interface
|
||||
|
||||
// EncodeError encodes an error response.
|
||||
func EncodeError(_ context.Context, err error, w http.ResponseWriter) {
|
||||
w.Header().Set("Content-Type", ContentType)
|
||||
if sdkErr, ok := err.(errors.SDKError); ok {
|
||||
w.WriteHeader(sdkErr.StatusCode())
|
||||
if err := json.NewEncoder(w).Encode(sdkErr); err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var wrapper error
|
||||
if errors.Contains(err, apiutil.ErrValidation) {
|
||||
wrapper, err = errors.Unwrap(err)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", ContentType)
|
||||
switch {
|
||||
case errors.Contains(err, svcerr.ErrAuthorization),
|
||||
errors.Contains(err, svcerr.ErrDomainAuthorization),
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -20,7 +21,7 @@ import (
|
||||
svcerr "github.com/absmach/supermq/pkg/errors/service"
|
||||
)
|
||||
|
||||
var errLimitExceeded = errors.New("limit exceeded")
|
||||
var errFailedToRead = errors.New("failed to read callout response body")
|
||||
|
||||
type Config struct {
|
||||
URLs []string `env:"URLS" envDefault:"" envSeparator:","`
|
||||
@@ -158,7 +159,11 @@ func (c *callout) makeRequest(ctx context.Context, urlStr string, params map[str
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return errors.NewSDKErrorWithStatus(svcerr.ErrAuthorization, resp.StatusCode)
|
||||
msg, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return errors.NewSDKErrorWithStatus(errors.Wrap(errFailedToRead, err), http.StatusInternalServerError)
|
||||
}
|
||||
return errors.NewSDKErrorWithStatus(errors.New(string(msg)), resp.StatusCode)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -181,7 +186,7 @@ func (c *callout) Callout(ctx context.Context, op string, pl map[string]interfac
|
||||
// if any request fails, we return the error immediately
|
||||
for _, url := range c.urls {
|
||||
if err := c.makeRequest(ctx, url, pl); err != nil {
|
||||
return errors.Wrap(errLimitExceeded, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user