# How to use Message with an error string without predefining it first?

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
];

• You could try writing to the $Messages channel using OpenWrite and Write. – Sjoerd C. de Vries Nov 27 '14 at 23:40 • You could use Assert instead of the If statements and define an $AssertFunction that Throws an error message. – Karsten 7. Nov 28 '14 at 1:45
• @Karsten7. Yes, I could do that. But it is more complicated, and according to accepted answer in what-are-the-best-practices-most-common-idiomatic-ways-to-report-errors-in-m this is not recommended way, which I agree. Someone have to catch the error. I was looking for simple basic method, and I think Message[] does the job well. – Nasser Nov 28 '14 at 1:52

General::error = "1";

foo[x_] := Module[{}, If[x < 0, Message[foo::error, "x<0 detected"], x]];

foo::error: x<0 detected