Skip to content

Commit 8511e91

Browse files
committed
Improve ParseTime mismatched format and value
1 parent 8afe6fb commit 8511e91

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

pkg/utils/parse_time.go

+10-5
Original file line numberDiff line numberDiff line change
@@ -74,12 +74,17 @@ func ParseTime(value any, timeOutputFormat string) (time.Time, error) {
7474
return time.Unix(0, value_i64), nil
7575
}
7676
default:
77-
value_string := value.(string)
78-
timeValue, err := timefmt.Parse(value_string, timeOutputFormat)
79-
if err != nil {
80-
return time.Time{}, err
77+
switch value.(type) {
78+
case string:
79+
value_string := value.(string)
80+
timeValue, err := timefmt.Parse(value_string, timeOutputFormat)
81+
if err != nil {
82+
return time.Time{}, err
83+
}
84+
return timeValue, nil
85+
default:
86+
return time.Time{}, fmt.Errorf("ParseTime expected string value for custom parsing format: timeOutputFormat:%s, value:%s (%s)", timeOutputFormat, fmt.Sprint(value), reflect.TypeOf(value))
8187
}
82-
return timeValue, nil
8388
}
8489
return time.Time{}, fmt.Errorf("timeOutputFormat not supported yet %s", timeOutputFormat)
8590
}

pkg/utils/parse_time_test.go

+8
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,12 @@ func TestParseTime(t *testing.T) {
7171
}
7272
})
7373
}
74+
75+
t.Run("Error on incoherent format and value", func(t *testing.T) {
76+
value := 1711629296987654321
77+
format := "%Y-%m-%d %H:%M:%S.%f"
78+
_, err := ParseTime(value, format)
79+
80+
assert.ErrorContains(err, fmt.Sprintf("ParseTime expected string value for custom parsing format: timeOutputFormat:%s, value:%s (%s)", format, fmt.Sprint(value), "int"))
81+
})
7482
}

0 commit comments

Comments
 (0)