Take the 2-minute tour ×

I have a method that is called when an exception is thrown. Only the Exception.ToString() is passed to it. It is not possible at this time to change the parameters to accept an Exception instead of a string, because we would have to change a lot of pages and I have no control over that (please I don't need anyone telling me to do that, because trust me I would love to just do that). We already have a class that handles the exceptions, but I have the opportunity to update this method and I wanted to know if it was possible to grab the last exception using reflection or using HttpContext.Current.Server.GetLastError(). With the GetLastError() it does not work because the exception was handled. Is there a way around this maybe with reflection or something? Any help is greatly appreciated. If this was discussed before, please show me because I was unable to find a similar question.

share|improve this question
Can you store the last exception before it clears in session? There is no way to get the last error without using GetLastError(). –  Brian Mains Feb 8 '12 at 15:57
Sadly no. The other solution I've thought of was to recreate it using this stackoverflow.com/questions/3810111/exception-and-reflection with the toString() details –  pqsk Feb 8 '12 at 16:00
add comment

1 Answer

up vote 0 down vote accepted

Quick fast solution I used for now (using some info from Exception and Reflection):

 string typeName = err.Substring(0, err.IndexOf(":"));
 string message = err.Length > typeName.Length + 2 ? err.Substring(err.IndexOf(":") + 1) : string.Empty;
 Type type = Type.GetType(typeName);
 ConstructorInfo ctor = type.GetConstructor(new[] { typeof(string) });
 object exception = ctor.Invoke(new object[] { message });

string err is the Exception.ToString(), which will have the type of exception and then I make the message the rest of the tostring method. This will do actually. If I wanted to be really explicit I could have used reflection to edit each property, but there is room for error there and the tostring actually will have everything and since I am creating the exception type it's all good in the hood. :) Hope this helps someone

share|improve this answer
add comment

Your Answer


