Sometimes you just need to edit/replace the original exception.
In my case the ArgumentException
for the JavaScriptSerializer.Deserialize()
method would return the FULL input as part of the error message if it was invalid.
Since you can't edit an exception, you need to recreate the exception with edited inputs and throw that new exception.
You will lose the original stack trace but if the exception is caught close to the source then it should be close enough.
First get the exception type you want to edit.
catch (Exception ex)
{
ex.GetType(); // This will return the exception type you need to catch
}
And then catch and recreate it.
catch (ArgumentException ex)
{
// The error handler seems to be willing to dump out the FULL input data when throwing an exception so we truncate the data.
const int MAX_DATA_IN_MESSAGE = 80;
if (String.IsNullOrEmpty(data) || data.Length < MAX_DATA_IN_MESSAGE || !ex.Message.Contains(data))
throw;
var truncatedData = data.Substring(0, MAX_DATA_IN_MESSAGE - 1) + "…";
var newMessage = ex.Message.Replace(data, truncatedData);
var newEx = new ArgumentException("Can't deserialize input, " + newMessage, ex.InnerException) { Source = ex.Source, HelpLink = ex.HelpLink };
throw newEx;
}