Files
simrsx-be/pkg/use-case-helper/use-case-helper.go
T
2025-08-21 16:24:48 +07:00

57 lines
1.1 KiB
Go

package usecasehelper
import (
"errors"
"fmt"
"strings"
pl "simrs-vx/pkg/logger"
"gorm.io/gorm"
)
func SafeToResponse[T any](data *T) any {
if data == nil {
return nil
}
// Use type assertion to call ToResponse if the type has it
if converter, ok := any(data).(interface{ ToResponse() any }); ok {
return converter.ToResponse()
}
return nil
}
func HandleReadError(err error, event *pl.Event, itemType string, id interface{}, data any) error {
if err == nil {
pl.SetLogInfo(event, data, "complete")
return nil
}
if errors.Is(err, gorm.ErrRecordNotFound) {
event.Status = "failed"
event.ErrInfo = pl.ErrorInfo{
Code: "data-notFound",
Detail: fmt.Sprintf("%s with ID %v not found", itemType, id),
Raw: err,
}
} else {
event.Status = "failed"
event.ErrInfo = pl.ErrorInfo{
Code: "data-read-detail-fail",
Detail: fmt.Sprintf("%s read failed", itemType),
Raw: err,
}
}
return pl.SetLogError(*event, nil)
}
func GetMiddlewareErrorCode(mwType MWType) string {
if strings.Contains(string(mwType), "Pre") {
return "MW_PRE_FAILED"
}
return "MW_POST_FAILED"
}