Skip to content

Commit a6c85d6

Browse files
author
Vadim Platonov
committed
convert: better error message
1 parent f42f8cf commit a6c85d6

File tree

2 files changed

+18
-8
lines changed

2 files changed

+18
-8
lines changed

src/java_time/convert.clj

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -66,13 +66,20 @@
6666
^TemporalUnit to-unit (jt.p/unit to-unit)]
6767
(if (= from-unit to-unit)
6868
{:whole amount, :remainder 0}
69-
(if (and (precise? from-unit) (precise? to-unit))
70-
(convert-unit (long amount)
71-
(-> from-unit .getDuration .toNanos)
72-
(-> to-unit .getDuration .toNanos))
73-
(convert-unit (long amount)
74-
(month-month-factor (jt.p/unit-key from-unit))
75-
(month-month-factor (jt.p/unit-key to-unit)))))))
69+
(cond (and (precise? from-unit) (precise? to-unit))
70+
(convert-unit (long amount)
71+
(-> from-unit .getDuration .toNanos)
72+
(-> to-unit .getDuration .toNanos))
73+
74+
(and (not (precise? from-unit)) (not (precise? to-unit)))
75+
(convert-unit (long amount)
76+
(month-month-factor (jt.p/unit-key from-unit))
77+
(month-month-factor (jt.p/unit-key to-unit)))
78+
79+
:else (-> (format "Cannot convert between precise (nanos up to weeks) and imprecise units, got: %s to %s!"
80+
from-unit to-unit)
81+
(IllegalArgumentException.)
82+
(throw))))))
7683

7784
(defn ^Date to-java-date
7885
"Converts a date entity to a `java.util.Date`."

test/java_time_test.clj

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -626,7 +626,10 @@
626626
(j/interval (j/offset-date-time 1970 1 1 0 0 0 0 +0)
627627
(j/offset-date-time 1970 1 1 0 0 1 0 +0))))
628628

629-
(is (= 1 (j/as (j/interval (j/instant 0) (j/instant 1)) :millis))))
629+
(is (= 1 (j/as (j/interval (j/instant 0) (j/instant 1)) :millis)))
630+
631+
(is (thrown-with-msg? IllegalArgumentException #"Cannot convert between.*"
632+
(j/as (j/interval (j/instant 0) (j/instant 1)) :months))))
630633

631634
(testing "operations"
632635
(is (= (j/interval 5000 10000)

0 commit comments

Comments
 (0)