PostSharp handle handled exceptions - exception

There are many Try/Catch blocks in my app to catch exceptions. I would like to read such handled exceptions and log them to a file. Is it possible to read handled exceptions with PostSharp?

no. PostSharp works by wrapping your methods in try/catch blocks of its own and then just rethrowing the exception. Any exceptions handled in your method would be an inner try/catch while postsharp would only have outer try/catch blocks. You would either 1) have to rethrow the exception or 2) Handle those exceptions using an aspect. Neither of which I recommend.

One way to handle this (!) is to have a method that you call within the catch that will log the parameters passed into the exception. Simply pass the exception in and the logger will log the information.
[LogParameters(LogLevel.Error)]
private static void Error(Exception ex) { }
public class LogParameters : OnMethodBoundaryAspect {
public override void OnEntry(MethodExcutionArgs args) {
for (int i=0; i<args.Arguments.Count; i++) {
// Get argument from args.Arguments.GetArgument(i)
}
}
}
Using the OnEntry method of a customized OnMethodBoundaryAspect, you can log the exception information by calling a method and passing in the exception. The method doesn't need to actually DO anything, it just is a dummy for the aspect to wrap around and log the exception parameter.

Related

JUnit - Catch an exception in the #After section

I have this scenario in which some tests can throw different exceptions.
#Test
public void addDevice(){
device.addDevice(); // this may throw exception 1
device.verifyStatus("Ready");
device.open(); // this may throw exception 2
device.verifyStatus("Open");
}
#Test
public void otherTest(){
device.act(); // this may throw exception 3
device.verifyStatus("Ready");
}
#After
public void tearDown(){
// handle the exception here
}
I want to handle those exceptions in the #After section without wrapping the test with try, catch.
Is that possible?
No, it is not possible.
You could wrap the test anyway with a try-catch-block. Then you could store the exception to a member variable instead of handling it.
In the #After method you can check whether the exception is null or not.
Due to your comment that you have hundreds of tests with this code I assume that this is set up logic which should actually be in an #Before method.
Thus, you could specify an external resource rule with a before and after method: https://github.com/junit-team/junit/wiki/Rules#externalresource-rules
In the before() method you perform the set up, catch and store the exceptions and in the after() method you handle them.
But does it make sense to handle the exception later? Can you run your test cases successfully if the set up fails?

Handling wrapped exception in Camel

class MyRouteBuilder extends SpringRouteBuilder {
public void configure() throws Exception {
//initialize camel context here
onException(ChildException.class)
.process(new ChildExceptionHandler())
.handled(true)
.to(errorURI);
onException(ParentException.class)
.process(new ParentExceptionHandler())
.handled(true)
.to(errorURI);
from(startURI)
.processRef("someBeanID")
//other processing here
}
}
Now my "someBeanID" throws ChildException while processing, but ParentExceptionHandler is being invoked for that. Code snippet in "someBeanID" is as below
try {
//some processing
throws new ParentException();
} catch (ParentException e) {
throw new ChildException(e); //being handled by ParentExceptionHandler (why?? should be ChildExceptionHandler??)
throw new ChildException(); //being handled by ChildExceptionHandler (should be)
}
It seems that whenever we wrap any exception, Camel automatically finds the actual wrapped exception and invokes handler for that, instead of invoking handler for wrapper exception. Why is this? Is there any problem in my code ??
Thanks,
Finally resolved....Refer to this
When trapping multiple exceptions, the order of the onException clauses is significant. Apache Camel initially attempts to match the thrown exception against the first clause. If the first clause fails to match, the next onException clause is tried, and so on until a match is found. Each matching attempt is governed by the following algorithm:
If the thrown exception is a chained exception (that is, where an exception has been caught and rethrown as a different exception), the most nested exception type serves initially as the basis for matching. This exception is tested as follows:
If the exception-to-test has exactly the type specified in the onException clause (tested using instanceof), a match is triggered.
If the exception-to-test is a sub-type of the type specified in the onException clause, a match is triggered.
If the most nested exception fails to yield a match, the next exception in the chain (the wrapping exception) is tested instead. The testing continues up the chain until either a match is triggered or the chain is exhausted.

Why ChannelOutboundHandler exceptions not caught by exceptionCaught() method? (Netty 4.0.4.Final)

(version: Netty 4.0.4.Final)
If an exception rises in ChannelInboundHandler, I can handle it in exceptionCaught() method but if the exception rises in ChannelOutboundHandler, I can't. Because, exceptionCaught() is not a call. Why is this so?
There is only way to handle outbound exception by analize Future result like this:
channel.writeAndFlush(serverPacket).addListener(new ChannelFutureListener() {
#Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
future.cause().printStackTrace();
}
}
});
But it is very inconveniently.
It's by design... Outbound operations only are notified via the Future as otherwise we would need to do double notifications which has some performance penalty. If you want to to have it propagated to the exceptionCaught handler you can just add the ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE as Listener to the returned ChannelFuture.

How can I wait on tasks without throwing TaskCanceledExceptions?

I have a method that creates some Tasks, and then waits on them with WaitAll before returning. The problem is, if those tasks got canceled, then WaitAll throws an AggregateException containing lots of TaskCanceledExceptions.
That means that WaitAll will throw exceptions in two different circumstances:
Exceptions that indicate a genuine error. These mean that there was a condition we didn't know how to handle; they need to propagate as unhandled exceptions, until they eventually terminate the process.
Exceptions that indicate that the user clicked a Cancel button. These mean that the task was canceled and cleaned up, and the program should continue running normally.
The latter fits squarely into the definition of a vexing exception: it's an exception thrown in a completely non-exceptional circumstance, so I have to catch it in order to resume normal control flow. Fortunately it's easy to catch, right? Just add catch (AggregateException) and -- oh wait, that's the same type that gets thrown when there's a fatal error.
I do need to wait for the tasks to finish running before I return (I need to know that they're no longer using their database connections, file handles, or anything else), so I do need the WaitAll or something similar. And if any of the tasks faulted, I do want those exceptions to propagate as unhandled exceptions. I just don't want exceptions for cancel.
How can I prevent WaitAll from throwing exceptions for canceled tasks?
The AggregateException provides a Handle method that can be used for these situations. If for example you want to ignore TaskCanceledException you can do:
var all = new AggregateException(
new NullReferenceException(),
new TaskCanceledException(),
new TaskCanceledException(),
new InvalidOperationException(),
new TaskCanceledException());
try
{
throw all;
}
catch (AggregateException errors)
{
errors.Handle(e => e is TaskCanceledException);
}
If all the exceptions are of type TaskCanceledException, the Handle method will not throw any exception; otherwise a new AggregateException containing only the unhandled exceptions will be thrown.
Based on João Angelo's suggestion, here goes a Task class extension
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MySharedLibrary.Extensions
{
public static class TaskExtensions
{
// This code is based João Angelo's stackoverflow suggestion https://stackoverflow.com/a/8681687/378115
// Use this when a CancellationTokenSource is used
public static void SafeWait(this Task TargetTask, CancellationTokenSource TargetTaskCancellationTokenSource)
{
if (TargetTaskCancellationTokenSource.IsCancellationRequested == false)
{
TargetTaskCancellationTokenSource.Cancel();
}
SafeWait(TargetTask);
}
// Use this when no CancellationTokenSource is used
public static void SafeWait(this Task TargetTask)
{
try
{
if (TargetTask.IsCanceled == false)
{
TargetTask.Wait();
}
}
catch (AggregateException errors)
{
errors.Handle(e => e is TaskCanceledException);
}
}
}
}

Communication between layers in an application

Let's assume we have the following method in the business layer. What's the best practice to tell the UI layer that something went wrong and give also the error message? Should the method return an empty String when it was OK, otherwise the error message, or should it throw another exception in the catch code wrapping the caught exception? If we choose the second variant then the UI should have another try,catch which is too much try,catch maybe. Here is a pseudocode for the first variant.
public String updateSomething()
{
try
{
//Begin transaction here
dataLayer.do1();
dataLayer.do2();
dataLayer.doN();
//Commit transaction code here
}
catch(Exception exc)
{
//Rollback transaction code here
return exc.message;
}
return "";
}
Is this a good practice or should I throw another exception in the catch(then the method will be void)?
I like to return a standard contract to my UI layer from my business layer.
It looks like this:
public class ServiceOperationResult<T>
{
public bool Successful
{
get;
set;
}
public ServiceErrorType ErrorType
{
get;
set;
}
public string ErrorMessage
{
get;
set;
}
public T ReturnData
{
get;
set;
}
}
I use generics so that every service can define what it sends back, and the standard error flags tell the client app what type of error occurred (these are a meta-type, like "Internal error", "External party error", "Business rule validation error") and the app can then react in a standard fashion to these error types.
For instance, business errors are displayed in a red error label, while internal errors get redirected to an error page (in a web app) or close the form (in a windows app)
My pet hate is seeing a red label on a web site (where I expect to see validation errors) and seeing something like "The database server refused your connection" This is the risk that you run by only using a string to return error data.
The best way is wrap exception in some more general type and rethrow it. So updateSomething() must declare that it can throw some sort of Exception (for example: UpdateFailedException) and in catch block you should wrap exception.
public String updateSomething() {
try {
[...]
} catch ( SQLException e ) {
// rollback;
throw new UpdateFailedException(e);
}
}
But catching abstract Exception type is not a good idea. You should wrap only those things which semantic you know. For example: SQLException, DataAccessException (Spring DAO) etc.
If you wrap Exception you easily could wrap InterruptedException of NullPointerException. And this can broke your application.
It's a little unusual to return a String like this (but there's no real reason not too). More usual methods would be:
return a boolean value, and have some method of setting the error message, either by logging it, setting some global "last error" value, or having a pointer to an error construct passed in to your method which you update;
have a void method which throws an exception on failure, and handle it in the calling code (as you suggest)
I have see both of the above used extensively. It's hard to say which is "best". Try to be consistent with the idioms and conventions of the language you are working in and/or the existing code set/libraries you are working with if any.
Probably the best way is to have a custom exception classes specific to layers, once you catch the exception in a particular layer throw the custom exception to the calling layer, having this will have you the following advantage.
you will get the better modular approach to deal with the exception.
the maintenance of the code will be easy when your code complexity increases
you will be having more control on the exception scenarios
for example you catch a exception in the business layer and want to inform Presentation layer
public string DummyFunction
{
try
{
}
catch(Exception ex)
{
throw new businessException();
}
}