lifedebugger's picture
Deploy files from GitHub repository
a3e77a9
package response
import (
"api.qobiltu.id/models"
"errors"
"strings"
"gorm.io/gorm"
)
func HandleGormError(err error, fallbackMessage string) error {
if err == nil {
return nil
}
if errors.Is(err, gorm.ErrRecordNotFound) {
return models.Exception{
Message: "Data not found",
DataNotFound: true,
Err: err,
}
}
lowerErr := strings.ToLower(err.Error())
if strings.Contains(lowerErr, "duplicated key") || strings.Contains(lowerErr, "unique constraint") || strings.Contains(lowerErr, "duplicate entry") {
return models.Exception{
Message: "Data already exists",
DataDuplicate: true,
Err: err,
}
}
if strings.Contains(lowerErr, "password") && strings.Contains(lowerErr, "length") {
return models.Exception{
Message: "Invalid password length",
InvalidPasswordLength: true,
Err: err,
}
}
if strings.Contains(lowerErr, "permission denied") || strings.Contains(lowerErr, "forbidden") {
return models.Exception{
Message: "Access forbidden",
Forbidden: true,
Err: err,
}
}
if errors.As(err, &gorm.ErrInvalidData) {
return models.Exception{
Message: "Invalid data format",
BadRequest: true,
Err: err,
}
}
return models.Exception{
Message: fallbackMessage,
InternalServerError: true,
Err: err,
}
}