Wolfram Research

WithMessageHandler

Contributed by: Taliesin Beynon

Source Notebook

Apply a custom handler to messages generated during evaluation

ResourceFunction["WithMessageHandler"][expr,f]

evaluates expr, applying f to Failure objects constructed out of messages generated during the evaluation.

Details and Options

ResourceFunction["WithMessageHandler"] has attribute HoldFirst.

Examples

Basic Examples

Print error message instead of issuing a message:

In[1]:=
ResourceFunction["WithMessageHandler"][1/0, Print]
Out[1]=

Abort after printing the first message:

In[2]:=
ResourceFunction[
 "WithMessageHandler"][{1/0, 1/0}, (Print[#]; Abort[]) &]
Out[2]=

Applications

Collect messages generated during evaluation in a list:

In[3]:=
Reap[ResourceFunction["WithMessageHandler"][1/0; 0^0; Transpose[{}]; expr, Sow[Extract[#[[2]], "MessageTemplate", HoldForm]] &]]
Out[3]=

Properties and Relations

Messages processed with WithMessageHandler are shielded from $MessageList and MessageList:

In[4]:=
ResourceFunction["WithMessageHandler"][0^0, Echo]; $MessageList
Out[4]=
In[5]:=
MessageList[-1]
Out[5]=

Compare with the standard evaluation:

In[6]:=
0^0; $MessageList
Out[6]=
In[7]:=
MessageList[-1]
Out[7]=

$MessagePrePrint receives only expressions that are included in the text of messages:

In[8]:=
Catch[Block[{$MessagePrePrint = Throw[HoldForm[#]] &}, 1/0;]]
Out[8]=

WithMessageHandler does not see messages that are suppressed, for instance, using Quiet:

In[9]:=
ResourceFunction["WithMessageHandler"][Quiet[0^0], Print]
Out[9]=

Resource History