PostSharp exception stack trace is not complete - postsharp

In the below code, args.Exception.ToString() (or args.Exception.StackTrace) returns only the method name and line where the exception is thrown but not the complete call stack.
public override void OnException(MethodExecutionArgs args)
{
Logger.GetLogger().Write(LogLevel.Error, args.Exception.ToString());
}
But the below code gives the complete callstack
catch (Exception ex)
{
Console.WriteLine(ex);
}
How can I get the full call stack in PostSharp with MethodExecutionArgs?

The issue is not with PostSharp but with my code. I had applied [SwallowException] on the whole assembly instead of at the caller.
Also, Logger.GetLogger().Write() supports multiline.
Thanks Jakub.

Related

Vert.x : How can i catch exception in handler onSuccess?

Here is my code:
private static void testExceptionInHandle() {
try {
var handler = future().onSuccess(v -> {
throw new RuntimeException("hello exception");
}).onFailure(e -> {
System.out.println("onFailure:" + e.getMessage());
});
} catch (Exception e) {
System.out.println("catch:" + e.getMessage());
}
}
I wonder what happened with an unpredictable exception but get nothing.
This causes the route processing method to not end properly.
This kind of runtime issues normally bubble up to the exception handler of the Vert.x context or of Vert.x itself (by default, it simply logs the exception).
To make sure the routing process finishes, you should setup a TimeoutHandler on your routes.
Otherwise, you can try using another programming model like Mutiny or RxJava. Any runtime exception will be reported to the subscriber (and then of course terminate the subscription).
You can define failureHandler on your route and catch all runtime exeptions. More details: https://vertx.io/docs/apidocs/io/vertx/ext/web/Route.html#failureHandler-io.vertx.core.Handler-

Skip exceptions in spring-batch and commit error in database

I'm using Spring batch to write a batch process and I'm having issues handling the exceptions.
I have a reader that fetches items from a database with an specific state. The reader passes the item to the processor step that can launch the exception MyException.class. When this exception is thrown I want to skip the item that caused that exception and continue reading the next one.
The issue here is that I need to change the state of that item in the database so it's not fetched again by the reader.
This is what I tried:
return this.stepBuilderFactory.get("name")
.<Input, Output>chunk(1)
.reader(reader())
.processor(processor())
.faultTolerant()
.skipPolicy(skipPolicy())
.writer(writer())
.build();
In my SkipPolicy class I have the next code:
public boolean shouldSkip(Throwable throwable, int skipCount) throws SkipLimitExceededException {
if (throwable instanceof MyException.class) {
// log the issue
// update the item that caused the exception in database so the reader doesn't return it again
return true;
}
return false;
}
With this code the exception is skipped and my reader is called again, however the SkipPolicy didn't commit the change or did a rollback, so the reader fetches the item and tries to process it again.
I also tried with an ExceptionHandler:
return this.stepBuilderFactory.get("name")
.<Input, Output>chunk(1)
.reader(reader())
.processor(processor())
.faultTolerant()
.skip(MyException.class)
.exceptionHandler(myExceptionHandler())
.writer(writer())
.build();
In my ExceptionHandler class I have the next code:
public void handleException(RepeatContext context, Throwable throwable) throws Throwable {
if (throwable.getCause() instanceof MyException.class) {
// log the issue
// update the item that caused the exception in database so the reader doesn't return it again
} else {
throw throwable;
}
}
With this solution the state is changed in the database, however it doesn't call the reader, instead it calls the method process of the processor() again, getting in an infinite loop.
I imagine I can use a listener in my step to handle the exceptions, but I don't like that solution because I will have to clone a lot of code asumming this exception could be launched in different steps/processors of my code.
What am I doing wrong?
EDIT: After a lot of tests and using different listeners like SkipListener, I couldn't achieve what I wanted, Spring Batch is always doing a rollback of my UPDATE.
Debugging this is what I found:
Once my listener is invoked and I update my item, the program enters the method write in the class FaultTolerantChunkProcessor (line #327).
This method will try the next code (copied from github):
try {
doWrite(outputs.getItems());
} catch (Exception e) {
status = BatchMetrics.STATUS_FAILURE;
if (rollbackClassifier.classify(e)) {
throw e;
}
/*
* If the exception is marked as no-rollback, we need to
* override that, otherwise there's no way to write the
* rest of the chunk or to honour the skip listener
* contract.
*/
throw new ForceRollbackForWriteSkipException(
"Force rollback on skippable exception so that skipped item can be located.", e);
}
The method doWrite (line #151) inside the class SimpleChunkProcessor will try to write the list of output items, however, in my case the list is empty, so in the line #159 (method writeItems) will launch an IndexOutOfBoundException, causing the ForceRollbackForWriteSkipException and doing the rollback I'm suffering.
If I override the class FaultTolerantChunkProcessor and I avoid writing the items if the list is empty, then everything works as intended, the update is commited and the program skips the error and calls the reader again.
I don't know if this is actually a bug or it's caused by something I'm doing wrong in my code.
A SkipListener is better suited to your use case than an ExceptionHandler in my opinion, as it gives you access to the item that caused the exception. With the exception handler, you need to carry the item in the exception or the repeat context.
Moreover, the skip listener allows you to know in which phase the exception happened (ie in read, process or write), while with the exception handler you need to find a way to detect that yourself. If the skipping code is the same for all phases, you can call the same method that updates the item's status in all the methods of the listener.

iText Receiving Default constructor cannot handle exception type IOException thrown by implicit super constructor. Must define an explicit constructor

Im stumped.Im trying to add an immage watermark in iText
I have received the above titled message when entering
Image watermark_image = Image.getInstance("c:/images/MyImage.png");
I have no idea how to define an explicit constructor in iText?
Im using the iTextg 5.5.9 jar file.
Any help is MOST appreciated.
Thank You
This is a general java error, not iText related.
You have two options.
Catch the exception
Image watermark_image = null;
try {
watermark_image = Image.getInstance("c:/images/MyImage.png");
} catch (IOException e) {
e.printStackTrace();
}
Or add a throws clause to your method definition:
public void getImageInstance() throws IOException {
watermark_image = Image.getInstance("c:/images/MyImage.png");
}

Assert exception from NUnit to MS TEST

I have some tests where i am checking for parameter name in exception.
How do i write this in MS TEST?
ArgumentNullException exception =
Assert.Throws<ArgumentNullException>(
() => new NHibernateLawbaseCaseDataLoader(
null,
_mockExRepository,
_mockBenRepository));
Assert.AreEqual("lawbaseFixedContactRepository", exception.ParamName);
I have been hoping for neater way so i can avoid using try catch block in the tests.
public static class ExceptionAssert
{
public static T Throws<T>(Action action) where T : Exception
{
try
{
action();
}
catch (T ex)
{
return ex;
}
Assert.Fail("Expected exception of type {0}.", typeof(T));
return null;
}
}
You can use the extension method above as a test helper. Here is an example of how to use it:
// test method
var exception = ExceptionAssert.Throws<ArgumentNullException>(
() => organizations.GetOrganization());
Assert.AreEqual("lawbaseFixedContactRepository", exception.ParamName);
Shameless plug, but I wrote a simple assembly that makes asserting exceptions and exception messages a little easier and more readable in MSTest using Assert.Throws() syntax in the style of nUnit/xUnit.
You can download the package from Nuget using: PM> Install-Package MSTestExtensions
Or you can see the full source code here: https://github.com/bbraithwaite/MSTestExtensions
High level instructions, download the assembly and inherit from BaseTest and you can use the Assert.Throws() syntax.
The main method for the Throws implementation looks as follows:
public static void Throws<T>(Action task, string expectedMessage, ExceptionMessageCompareOptions options) where T : Exception
{
try
{
task();
}
catch (Exception ex)
{
AssertExceptionType<T>(ex);
AssertExceptionMessage(ex, expectedMessage, options);
return;
}
if (typeof(T).Equals(new Exception().GetType()))
{
Assert.Fail("Expected exception but no exception was thrown.");
}
else
{
Assert.Fail(string.Format("Expected exception of type {0} but no exception was thrown.", typeof(T)));
}
}
More info here.
Since the MSTest [ExpectedException] attribute doesn't check the text in the message, your best bet is to try...catch and set an Assert on the exception Message / ParamName property.

NUnit & Exceptions

Is there anyway one can output to the console the message of an exception that may be throw during an NUnit test? Currently I use the ExpectedExceptionAttribute but that doesn't output the message itself, only checks it.
If Method doesn't throw test fails. If it throws it additionally writes exception message to the console.
[Test]
public void Method_throws_exception()
{
var ex = Assert.Throws<InvalidOperationException>(sut.Method);
Console.WriteLine(ex.Message);
}
That assert is only at tab tab with http://nuget.org/List/Packages/NUnit.Snippets
I use:
[Test]
public void SomeTest(){
try {
... stuff ...
Assert.Fail("ExpectedExceptionType should have been thrown");
} catch (ExpectedExceptionType ex) {
Console.WriteLine(ex);
// Assert.Stuff about the exception
}
}
However I've just noticed NUnit 2.6 and it's Exception Assertion helpers.