Fallback method error reporting

question

#1

In an API I ask the user to define custom types and also methods for them for a collection of functions. When this is not done, a MethodError is thrown automatically since nothing is defined, but I wonder if I could make this informative. Eg

using DocStringExtensions

"""
    $SIGNATURES

Define this to simulate values from your model.
"""
function simulate(model)
    warn("You need to define `simulate` for your model type.")
    throw(MethodError(simulate, model))
end

documents the signature automatically (DRY), and gives an informative warning:

julia> simulate(1.0)
WARNING: You need to define `simulate` for your model type.
ERROR: MethodError: no method matching simulate(::Float64)
Closest candidates are:
  simulate(::Any) at REPL[39]:2
Stacktrace:
 [1] simulate(::Float64) at ./REPL[39]:3

I wonder that the best practice is. Should I throw the MethodError, or just error with the same message?


#2

Related


#3

Thanks! It would be great to have that, but that’s probably post-v1.0. In the meantime, I ended up using

using MacroTools
macro no_method_info(ex)
    @capture(ex, f_(args__)) || error("Expected a function name with arguments")
    msg = "You need to define `$(string(f))` with this model type."
    esc_f = esc(f)
    esc_args = map(esc, args)
    quote
        function $esc_f($(esc_args...))
            info($msg)
            throw(MethodError($esc_f,
                              Tuple{$(map(e -> :(typeof($e)), esc_args)...)}))
        end
    end
end

EDIT: made arguments into a Tuple for MethodError.