How to use the "ThrowTerminatingError" method in cmdlet development? - powershell

When handling errors in my cmdlet development, I encounter an unexpected behavior of the ThrowTerminatingError method.
Calling the method results in an unhandled exception of PipelineStoppedException. Thus, I do not get a formatted error in PowerShell, but a long unhandled exception error message.
My code corresponds to the following structure:
protected override async void ProcessRecord()
{
try
{
var transferClient = new TransferClient(...);
var result = await transferClient.GetAsync(); // Throws an AuthenticationException
}
catch (AuthenticationException exception)
{
var record = new ErrorRecord(exception, "TestException", ErrorCategory.AuthenticationError, null);
ThrowTerminatingError(record); // Unhandled exception
}
}
System info:
Microsoft.PowerShell.SDK: 7.2.8
System.Management.Automation: 7.2.8
Target: PowerShell 7

Related

Entity Framework Async failing, no exception

Consider the code below. My foo line returns data. My bar line also returns data. However, if I were to comment out the foo line, then the bar line fails to return anything. It simply crashes the app without throwing an exception. Nor does it log anything in the Event Log.
Any thoughts as to why the Async method fails - only when not preceded by the non-Async?
private async Task<bool> MyTest() {
using(var cntx = new BoomiData.PantherDataContext(pantherConnectionString)) {
try {
//var foo = cntx.Manifests.FirstOrDefault();
var bar = await cntx.Manifests.FirstOrDefaultAsync();
}
catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
return true;
}

Capacitor plugin stop responding after exception

I'm using ionic and capacitor v2.5 for creating a plugin
I'm using the following code for catching unhandled exception in the capacitor plugin
public void load() {
super.load();
try {
Thread
.setDefaultUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread thread, Throwable e) {
PluginCall call = getSavedCall();
if (call != null) {
call.error("called failed:"+e.getMessage());
}
freeSavedCall();
}
});
} catch (SecurityException e) {
Log.e(Constants.TAG_MASTER,
"Could not set the Default Uncaught Exception Handler:"
+ e.getStackTrace());
}
}
my problem is that whenever there is an unhandled exception, the plugin stop to respond to calls from the ionic app.
The code operates as "expected" in a sense that gets the call from the method that throwed the exception and the call.error(..); is executed.
I can replicate that with the following code
public void foo(PluginCall call) {
saveCall(call);
throw new exception();
}
Any thoughts on why the plugin stops to respond after that?

Stopping a Windows Service in the event of a critical error

I have a Windows Service which basically wraps a task:
public partial class Service : ServiceBase
{
private Task task;
private CancellationTokenSource cancelToken;
public Service()
{
InitializeComponent();
this.task = null;
this.cancelToken = null;
}
protected override void OnStart(string[] args)
{
var svc = new MyServiceTask();
this.cancelToken = new CancellationTokenSource();
this.task = svc.RunAsync(cancelToken.Token);
this.task.ContinueWith(t => this.OnUnhandledException(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
}
protected override void OnStop()
{
if (this.task != null)
{
this.cancelToken.Cancel();
this.task.Wait();
}
}
private void OnUnhandledException(Exception ex)
{
this.EventLog.WriteEntry(string.Format("Unhandled exception: {0}", ex), EventLogEntryType.Error);
this.task = null;
this.Stop();
}
}
As you can see, the service can catch unhandled exceptions. If this happens, the exception is logged and the service is stopped. This has the effect of writing two messages to the event log - one error stating there was an unhandled exception, and another stating that the service was successfully stopped.
This may sound minor, but I'm hoping to be able to suppress the 'successfully stopped' message. I find it misleading - it suggests that the service stopping was a normal occurrence. Is there another way I can force the service to stop itself without this message being logged?

JUnit Eclipse check if exception is thrown?

hey guys i have this Junit test code for factorial
#org.junit.Test
public void testIterationAAA()
{
Iteration test = new Iteration("AAA");
int result = test.factorial("AAA");
assertEquals("exceptionMessage",result);
}
supposedly since a string's factorial cant be calculated the exception i made should be thrown but how to test it using Junit??
import org.junit.Assert;
...
#org.junit.Test
public void testIterationAAA()
{
try {
Iteration test = new Iteration("AAA");
int result = test.factorial("AAA");
// The above line is expected to throw an exception.
// If the code does not throw an exception, fail the test.
Assert.fail("An exception should have been thrown");
} catch (Exception ex) {
// Nothing to do. Exception was expected in this test case.
}
}
You should use expected attribute
#Test(expected=SomeException.class)

Testing for exception thrown in several lines

I would like to test a method, in JUnit4, that does not pass at the first caught exception, but if all calls to the tested method throw exception. And I would like to know if this is possible.
I explain : let us say I have the method
public void setFromFen(String fenValue) throws IllegalArgumentException
in a class Position.
In PositionTest Junit4 class, I would like to do something like this :
#Test(expected=IllegalArgumentException.class){
...
setFromFen("2"); // throws IllegalArgumentException
setFromFen("8/8/8/8/8/8/8/8"); // does not throw IllegalArgumentException
...
}
so that the test only succeed if all calls to setFromFen fail.
In this case, though the second test does not throw IllegalArgumentException, the test succeed : and that's not what I want.
Is is it possible to get success only if all tests lines throws IllegalArgumentException ?
I think this is outside of the possibilities of the annotation.
You'll probably need something along these lines:
#Test
public void thatAllCallsFail() {
int failureCount = 0;
try {
setFromFen(this.sampleString1);
}
catch( final Exception e ) {
failureCount++;
}
try {
setFromFen(this.sampleString1);
}
catch( final Exception e ) {
failureCount++;
assertEquals("All 2 calls should have failed", failureCount, 2);
}
}
I'm not for a second suggesting that that is a nice way of doing it.
If you're looking for a more generic solution, perhaps adding your strings to a collection and looping over them...
#Test
public void thatAllCallsFail2() {
final String[] strings = new String[] { sampleString1, sampleString2 };
int failureCount = 0;
for (final String string : strings) {
try {
setFromFen(string);
}
catch( final Exception e ) {
failureCount++;
}
}
assertEquals("All " + strings.length + " calls should have failed", failureCount, strings.length);
}
Of course, neither of these solutions will tell you which call did not throw an exception if the tests were to fail.