Skip to content

Commit 156ffe2

Browse files
committed
If a unit call bubbles up to unit(::Any), throw a DomainError
This allows us to remove the type restriction on T for unit(::Type{Union{Missing,T}}), making it possible for users to define unit on their own types, while at the same time giving a more descriptive error message than StackOverflowError.
1 parent fe1e225 commit 156ffe2

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

src/utils.jl

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,9 +139,22 @@ julia> unit(1.0) == NoUnits
139139
true
140140
```
141141
"""
142+
143+
"""
144+
This is shown if a user has not defined units for their quantity type.
145+
"""
146+
const MISSING_UNIT_DEFINITION_MESSAGE =
147+
"""
148+
You tried calling unit on an object that has none defined.
149+
Not everything has (or should have) units.
150+
If your type should have units, define a method of unit on them.
151+
"""
152+
153+
@inline unit(x::Any) = throw( DomainError( x, MISSING_UNIT_DEFINITION_MESSAGE ) )
154+
@inline unit(x::Type{Any}) = throw( DomainError( x, MISSING_UNIT_DEFINITION_MESSAGE ) )
142155
@inline unit(x::Number) = NoUnits
143156
@inline unit(x::Type{T}) where {T <: Number} = NoUnits
144-
@inline unit(x::Type{Union{Missing, T}}) where {T <: Union{Number, Dates.FixedPeriod}} = unit(T) # Type restriction required here for T, or might result in infinite recursion.
157+
@inline unit(x::Type{Union{Missing, T}}) where T = unit(T) # Type restriction required here for T, or might result in infinite recursion.
145158
@inline unit(x::Type{Missing}) = missing
146159
@inline unit(x::Missing) = missing
147160

test/dates.jl

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,14 @@
1212
@test_throws MethodError dimension(T(1))
1313
@test_throws MethodError Unitful.numtype(T)
1414
@test_throws MethodError Unitful.numtype(T(1))
15-
@test_throws MethodError unit(T)
16-
@test_throws MethodError unit(T(1))
15+
@test_throws DomainError unit(T)
16+
@test_throws DomainError unit(T(1))
1717
end
1818

1919
for p = (CompoundPeriod, CompoundPeriod(), CompoundPeriod(Day(1)), CompoundPeriod(Day(1), Hour(-1)))
2020
@test dimension(p) === 𝐓
2121
@test_throws MethodError Unitful.numtype(p)
22-
@test_throws MethodError unit(p)
22+
@test_throws DomainError unit(p)
2323
end
2424
end
2525

0 commit comments

Comments
 (0)