I need a very simple error reporting using Message. But I do not want to pre-define each error message separately as shown What are the best practices / most common / idiomatic ways to report errors in Mathematica? for example, and in many other places.
I'd like to just do Message["my error message"]
or something like this, without having to do foo::message1="...."
and foo::message2="...."
and then later write Message[foo::message1]
or Message[foo::message2]
. This will be specific to one module, so I do not need to share these messages with other modules.
Here is an example that works, but require one to define name for the message first:
foo[x_] := Module[{},
foo::error = "x<0 detected";
If[x < 0, Message[foo::error], x]
];
r = foo[-1]
I'd like to be something like
foo[x_] := Module[{},
If[x < 0, Message["x<0 detected"], x]
];
But the above does not work.
Is there a syntax that allows one to build the Message on the fly without predefining it first?
I tried foo::"argx"
which is supposed to allow one on the fly to build a message, but ofcourse the message now does not mean what I want:
foo[x_] := Module[{},
If[x < 0, Message[foo::"argx", "foo", "x<0 detected"], x]
];
r = foo[-1]
If it is not possible to do with Message
, is there something similar to Message
that allows me to issue error message but leave the function unevaluated? I do not want to use Throw/Catch, etc.. I want to keep things simple for now.
Update:
Karsten 7 method in answer below seems to work well. I only need to define one named message, so no problem. This is what I can do now:
foo[x_] := Module[{},
General::error = "`1`";
If[x < 0, Message[foo::error, "x<0 detected"]; Return[]];
If[x > 10, Message[foo::error, "x>10 detected"]; Return[]];
(*all checked, now apply the algorithm*)
x
];
$Messages
channel usingOpenWrite
andWrite
. $\endgroup$Assert
instead of theIf
statements and define an$AssertFunction
thatThrow
s an error message. $\endgroup$