diff --git a/src/Simulation/Simulators.Tests/StackTraceTests.cs b/src/Simulation/Simulators.Tests/StackTraceTests.cs index c3fead7b586..e429475cfb9 100644 --- a/src/Simulation/Simulators.Tests/StackTraceTests.cs +++ b/src/Simulation/Simulators.Tests/StackTraceTests.cs @@ -381,6 +381,19 @@ public void ErrorLogTest() Assert.StartsWith(" at Microsoft.Quantum.Simulation.Simulators.Tests.Circuits.AlwaysFail4 on", logs[5]); Assert.Equal("", logs[6]); } + + logs.Clear(); + sim.EnableStackTracePrinting = false; + try + { + QVoid res = sim.Execute(QVoid.Instance); + } + catch (ExecutionFailException) + { + Assert.Equal(2, logs.Count); + Assert.StartsWith("Unhandled exception. Microsoft.Quantum.Simulation.Core.ExecutionFailException: Always fail", logs[0]); + Assert.Equal("", logs[1]); + } } } } \ No newline at end of file diff --git a/src/Simulation/Simulators/QuantumSimulator/SimulatorBase.cs b/src/Simulation/Simulators/QuantumSimulator/SimulatorBase.cs index eb8b27f1ee6..c84cb17936f 100644 --- a/src/Simulation/Simulators/QuantumSimulator/SimulatorBase.cs +++ b/src/Simulation/Simulators/QuantumSimulator/SimulatorBase.cs @@ -55,6 +55,13 @@ public abstract class SimulatorBase : Factory, IOperationFacto public abstract string Name { get; } + /// + /// When exception printing is enabled, the value of this property controls stack trace printout. + /// When set to true (default), the stack trace is printed in addition to the exception message." + /// When set to false, the exception message is printed without the stack trace." + /// + public bool EnableStackTracePrinting { get; set; } = true; + /// /// If the execution finishes in failure, this method returns the call-stack of the Q# operations /// executed up to the point when the failure happened. @@ -140,12 +147,15 @@ public override AbstractCallable CreateInstance(Type t) protected void WriteStackTraceToLog(Exception exception, IEnumerable callStack) { OnLog?.Invoke($"Unhandled exception. {exception.GetType().FullName}: {exception.Message}"); - var first = true; - foreach (var sf in callStack) + if (EnableStackTracePrinting) { - var msg = (first ? " ---> " : " at ") + sf.ToStringWithBestSourceLocation(); - OnLog?.Invoke(msg); - first = false; + var first = true; + foreach (var sf in callStack) + { + var msg = (first ? " ---> " : " at ") + sf.ToStringWithBestSourceLocation(); + OnLog?.Invoke(msg); + first = false; + } } OnLog?.Invoke(""); }