-2

I have a query handler decorator which logs any exceptions:

public class QueryHandlerLogDecorator<TQuery, TResult> : IQueryHandler<TQuery, TResult>
    where TQuery : IQuery<TResult>
{
    private readonly IQueryHandler<TQuery, TResult> _handler;
    private readonly ILog _log;

    public QueryHandlerLogDecorator(IQueryHandler<TQuery, TResult> handler)
    {
       _handler = handler;
       _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
    }

    public TResult Handle(TQuery query)
    {
        try
        {
             var result = _handler.Handle(query);

            _log.Info("Ok");

            return result;
        }
        catch (Exception ex)
        {
            _log.Error(ex.Message, ex);                

            throw new Exception(ex.Message);
        }
    }
}

Whilst the exception handling isn't the worst thing in the world, what it means is that I lose the type of the exception being thrown.

For example, if I throw ApplicationException lower down in the application, this is caught and rethrown as Exception.

How can I rethrow the exception being caught as the original type?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Graham
  • 1,497
  • 2
  • 16
  • 36

2 Answers2

0

Rethrow the exception by just using the throw keyword. This will rethrow the exception as passed to the exception handler.

public TResult Handle(TQuery query)
{
    try
    {
         var result = _handler.Handle(query);

        _log.Info("Ok");

        return result;
    }
    catch (Exception ex)
    {
        _log.Error(ex.Message, ex);                
        throw;
    }
}
Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
0

You can just use throw; instead of throw new... or instead of throw ex;

Once an exception is thrown, part of the information it carries is the stack trace. The stack trace is a list of the method call hierarchy that starts with the method that throws the exception and ends with the method that catches the exception. If an exception is re-thrown by specifying the exception in the throw statement, the stack trace is restarted at the current method and the list of method calls between the original method that threw the exception and the current method is lost. To keep the original stack trace information with the exception, use the throw statement without specifying the exception.

More here : MSDN

Zein Makki
  • 29,485
  • 6
  • 52
  • 63