Files
hatchet/pkg/integrations/shared/webhookutils/errors.go
Alexander Belanger 366c79441d first commit
2023-12-15 13:08:04 -05:00

85 lines
1.4 KiB
Go

package webhookutils
import (
"encoding/json"
"errors"
"net/http"
hatcheterrors "github.com/hatchet-dev/hatchet/pkg/errors"
"github.com/rs/zerolog"
)
type ErrorOpts struct {
Code uint
}
func HandleAPIError(
l *zerolog.Logger,
alerter hatcheterrors.Alerter,
w http.ResponseWriter,
r *http.Request,
err error,
writeErr bool,
) {
// if the error is of type detailed error, get the code from that
detailedErr := hatcheterrors.DetailedError{}
if ok := errors.As(err, &detailedErr); ok {
if detailedErr.Code == 0 || detailedErr.Code >= http.StatusInternalServerError {
handleInternalError(
l,
alerter,
w,
r,
detailedErr,
writeErr,
)
return
} else {
w.WriteHeader(int(detailedErr.Code))
writerErr := json.NewEncoder(w).Encode(detailedErr)
if writerErr != nil {
handleInternalError(
l,
alerter,
w,
r,
writerErr,
false,
)
return
}
}
return
}
return
}
func handleInternalError(l *zerolog.Logger,
alerter hatcheterrors.Alerter,
w http.ResponseWriter,
r *http.Request,
err error,
writeErr bool) {
event := l.Warn().
Str("internal_error", err.Error())
event.Send()
data := make(map[string]interface{})
data["method"] = r.Method
data["url"] = r.URL.String()
alerter.SendAlert(r.Context(), err, data)
w.WriteHeader(http.StatusInternalServerError)
return
}