I have extended NLog to log all items in the Exception.Data collection. So, when I catch an SqlException, in my data access code, I like to add a few items to the Exception.Data dictionary to provide better logging. I don't always want to log from within the catch, but instead, let the exception bubble up and be handled later. So I write something like this:
Try
...
Catch exception As Exception
exception.Data.Add("SP", StoreProcedureNameCost)
exception.Data.Add("Connection", myConnection.ConnectionString)
Throw
End Try
Does calling just Throw instead of Throw exception still have have all of my added Data items?
Yes, It will preserve the changes made to Data property. The fundamental difference between throw and throw ex is that the stack trace does not change with calling throw whereas it gets changed with throw ex.
I gave it a try myself and it works like I hoped. Just calling throw DOES preserve new data added to the exception:
Try
Try
Throw New NotImplementedException("Hi")
Catch ex As Exception
ex.Data.Add("Here", "It is there")
Throw
End Try
Catch ex As Exception
Dim msg As String = ex.Data("Here").ToString()
Response.Write(msg)
End Try
It worked and spit out "It is there".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With