0

I'm incorporating telemetry into my product on all service requests, unfortunately that includes exceptions. A problem I'm having is I surround my requests with a try-catch and if it's successful I log the request and if there's a catch I log the exception than throw the exception so that it still gets propagated up so that it can be debugged. A problem I'm having is that with try-catch I lose all the original data from the original exception caught by my try-catch, which I think would be nice to propagate back up.

public void someFunction(object data)
{
    try 
    {
        var response = await request(data);
        LogInformation(request: data, response: response);
    }
    catch (Exception e)
    {
         throw HandleAndLogException(data, e);
    }
}

private HttpResponseException HandleAndLogException(object data, Exception e)
{
    LogException(data: data, response: e.Message);

    var resp = new HttpResponseMessage(HttpStatusCode.BadRequest) { 
        Content = new StringContent(e.Message) 
    };

    return new HttpResponseException(resp);
}

So as you can see I create a new HttpResponseException and just append the message to it, but I'd rather propagate back up the exception thrown in it's entirety.

Gooby
  • 621
  • 2
  • 11
  • 32
  • 4
    Possible duplicate of [Is there a difference between "throw" and "throw ex"?](https://stackoverflow.com/questions/730250/is-there-a-difference-between-throw-and-throw-ex) – mjwills Mar 28 '19 at 03:16
  • Looks strange to me overall. You have a random void function throwing a `HttpResponseException`. Why not just log error and throw normal `Exception` using `throw` and let the correct layer handle the error properly(be it sending the error back to a client or something else). Anyway, check if [this](https://stackoverflow.com/questions/12519561/throw-httpresponseexception-or-return-request-createerrorresponse) helps. Otherwise, can;t you serialize the whole exception into `StringContent()`? – kovac Mar 28 '19 at 04:13

1 Answers1

0

If you want to do something clever/evil, you can use the when keyword to introduce logging without breaking the stack trace on your exception.

See when contextual keyword in the C# reference on MSDN. It's supposed to be used as a filter (the method returns true or false, indicating whether that catch block should be used) but you can do whatever you want with

I think this is what you'd want, although I haven't tested it:

public void someFunction(object data)
{
    try 
    {
        var response = await request(data);
        LogInformation(request: data, response: response);
    }
    catch (Exception e) when (HandleAndLogException(data, e))
    {
         throw;
    }
}

private bool HandleAndLogException(object data, Exception e)
{
    LogException(data: data, response: e.Message);
    return true;
}
Guttsy
  • 2,130
  • 1
  • 18
  • 29