Currentlly I'm using this approach to convert an exception to an exception that will translate the original exception message to English language:
C#:
[DebuggerStepThrough()]
[Extension()]
public Exception ToEnglish<T>(T ex) where T : Exception
{
CultureInfo oldCI = Thread.CurrentThread.CurrentUICulture;
Exception exEng = default(Exception);
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
// Instance Exception one time to retrieve an English message.
exEng = (Exception)Activator.CreateInstance(ex.GetType);
// Instance Exception a second time to pass additional parameters to its constructor.
exEng = (Exception)Activator.CreateInstance(ex.GetType, new object[] {
exEng.Message,
ex
});
Thread.CurrentThread.CurrentUICulture = oldCI;
return exEng;
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//=======================================================
Vb.Net:
<DebuggerStepThrough>
<Extension>
Public Function ToEnglish(Of T As Exception)(ByVal ex As T) As Exception
Dim oldCI As CultureInfo = Thread.CurrentThread.CurrentUICulture
Dim exEng As Exception
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US")
' Instance Exception one time to retrieve an English message.
exEng = DirectCast(Activator.CreateInstance(ex.[GetType]), Exception)
' Instance Exception a second time to pass additional parameters to its constructor.
exEng = DirectCast(Activator.CreateInstance(ex.[GetType], New Object() {exEng.Message, ex}), Exception)
Thread.CurrentThread.CurrentUICulture = oldCI
Return exEng
End Function
( I'm aware that some exception messages are only partially defined in English )
However, I'm not totally satisfied with the results, because firstlly I'm not returning the same runtime type, and secondlly the stack-trace of the resulting exception is empty so I need to to preserve the info of the original exception in the InnerException
property of the resulting exception.
Then, I would like to improve the function to meet there requeriments:
-
- Return an Exception of the same Type that passed to the type-parameter (eg.
FileNotFoundException
).
- Return an Exception of the same Type that passed to the type-parameter (eg.
-
- In the resulting exception, re-create/preserve the stack-trace (and
TargetSite
property), in English language.
- In the resulting exception, re-create/preserve the stack-trace (and
I'm not really sure if point number 2 could be accomplished because possible stack limitations?, anyways I'm asking to know, how I could do both things?.
Aucun commentaire:
Enregistrer un commentaire