Function Repository Resource:

WithMessageHandler

Source Notebook

Apply a custom handler to messages generated during evaluation

Contributed by: Taliesin Beynon

ResourceFunction["WithMessageHandler"][expr,f]

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

Details and Options

ResourceFunction["WithMessageHandler"] has attribute HoldFirst.

Examples

Basic Examples (2) 

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 (1) 

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 (3) 

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

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 06 February 2019

Related Resources

License Information