I used the following years. I donβt know if there is a less βdodgyβ way to achieve this in more modern .Net infrastructures:
public void PreserveStackTrace(Exception ex) { MethodInfo preserve = ex.GetType().GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic); preserve.Invoke(ex,null); }
To use this:
[WebMethod] public void ExceptionTest() { try { throw new Exception("An Error Happened"); } catch (Exception ex) { evlWebServiceLog.WriteEntry(ex.ToString(), EventLogEntryType.Error); PreserveStackTrace(ex); throw ex; } }
Update : based on @dcastro's comment, I would suggest that the extension method is at 4.5 (at <4.5 it could still be an extension wrapping the above method):
public static void ReThrow(this Exception ex) { var exInfo = ExceptionDispatchInfo.Capture(ex); exInfo.Throw(); }
So you just have:
catch (Exception ex) { evlWebServiceLog.WriteEntry(ex.ToString(), EventLogEntryType.Error); ex.ReThrow(); }
source share