diff --git a/docs/src/manual/nonlinear.md b/docs/src/manual/nonlinear.md index dcba37b45d5..afd11e58876 100644 --- a/docs/src/manual/nonlinear.md +++ b/docs/src/manual/nonlinear.md @@ -370,7 +370,7 @@ x² - 0.2 x + 0.010000000000000002 julia> typeof(f) QuadExpr (alias for GenericQuadExpr{Float64, GenericVariableRef{Float64}}) ``` -To over-ride this behavior, use the [`@force_nonlinear`](@ref) macro: +To override this behavior, use the [`@force_nonlinear`](@ref) macro: ```jldoctest force_nonlinear julia> g = @force_nonlinear((x - 0.1)^2) (x - 0.1) ^ 2 diff --git a/src/macros/@force_nonlinear.jl b/src/macros/@force_nonlinear.jl index 530bccf7e80..5ea1dfde2a7 100644 --- a/src/macros/@force_nonlinear.jl +++ b/src/macros/@force_nonlinear.jl @@ -108,11 +108,14 @@ macro force_nonlinear(expr) end return x end - return quote - r = $(esc(ret)) - if !(r isa $GenericNonlinearExpr) - $error_fn("expression did not produce a GenericNonlinearExpr") - end - r - end + return Expr(:call, _force_nonlinear, error_fn, esc(ret)) +end + +_force_nonlinear(::F, ret::GenericNonlinearExpr) where {F} = ret + +function _force_nonlinear(error_fn::F, ret::Any) where {F} + return error_fn( + "expression did not produce a `GenericNonlinearExpr`. Got a " * + "`$(typeof(ret))`: $(ret)", + ) end diff --git a/test/test_macros.jl b/test/test_macros.jl index 0ea3fb23efc..9a144f7126d 100644 --- a/test/test_macros.jl +++ b/test/test_macros.jl @@ -2373,7 +2373,7 @@ function test_force_nonlinear() @test @force_nonlinear(x^2) isa GenericNonlinearExpr @test_throws_runtime( ErrorException( - "In `@force_nonlinear(x)`: expression did not produce a GenericNonlinearExpr", + "In `@force_nonlinear(x)`: expression did not produce a `GenericNonlinearExpr`. Got a `$(typeof(x))`: $x", ), @force_nonlinear(x), )