Handling Errors in Post Simulation Callbacks
Today I want to share a simple trick I recently recommended to a user who was struggling with retrieving error messages from simulations.
The Problem
What this user described is that, when simulating a model using the play button, if the model errors out, a clear error message is displayed in the Diagnostics Viewer:
![](https://blogs.mathworks.com/simulink/files/postSimTips_1-1.png)
However, when simulating the model using the sim command and a post-simulation function, the error was not as useful.
Here is a simplified version of the code simulating the model:
mdl = 'ex_modeling_simple_system';
in = Simulink.SimulationInput(mdl);
in = in.setPostSimFcn(@myPostSim);
out = sim(in,'ShowSimulationManager','on');
Where the post-simulation function adds to the SimulationOutput object additional post-processed information:
![](https://blogs.mathworks.com/simulink/files/postSimTips_2-1.png)
The error message is not very useful:
![](https://blogs.mathworks.com/simulink/files/postSimTips_3-1.png)
This same error message is also displayed in the Simulation Manager:
![](https://blogs.mathworks.com/simulink/files/postSimTips_4-1.png)
The Explanation
If you put a breakpoint in the post-simulation function, you will see that the "dot indexing" error is happening because the simulation errors out and the "logsout" field my code is trying to access does not exist.
![](https://blogs.mathworks.com/simulink/files/postSimTips_5-1.png)
The Solution
To avoid that, what I recommend is looking at the ErrorMessage field of the SimulationOutput object, and access the logged data only if there is no error:
![](https://blogs.mathworks.com/simulink/files/postSimTips_6-1.png)
That way, the Simulation Manager will display the original error:
![](https://blogs.mathworks.com/simulink/files/postSimTips_7-1.png)
This technique is especially useful if you are simulating the model on parallel workers using parsim, because it's not possible to interactively debug code running on parallel workers as I did here.
Now it's your turn
I would be curious to hear from you: should we implement such error handling around the post-simulation function to automatically return the actual simulation error instead of the post-simulation error when the simulation errors out?
Let us know in the comments below.
댓글
댓글을 남기려면 링크 를 클릭하여 MathWorks 계정에 로그인하거나 계정을 새로 만드십시오.