Reputation: 73
Is there a way to find out which property of the objects threw the exception. I have a Class with 3 properties. I want to give a message to the user that a particular property in the class is wrong.
public class Numbers
{
public string Num1 { get; set; }
public string Num2 { get; set; }
public string Num3 { get; set; }
}
class Program
{
static void Main(string[] args)
{
var numbers = new Numbers() { Num1 = "22", Num2 = "err", Num3 = "33" };
// Call an extension method which tries convert to Int
var num = numbers.Num1.StringToInt();
num = numbers.Num2.StringToInt();
num = numbers.Num3.StringToInt();
Console.WriteLine(num);
Console.ReadLine();
}
}
public static class SampleExtension
{
static StackTrace stackTrace = new StackTrace(true);
// Extension method that converts string to Int
public static int StringToInt(this string number)
{
try
{
// Intentionally used 'Convert' instead of 'TryParse' to raise an exception
return Convert.ToInt32(number);
}
catch (Exception ex)
{
// Show a msg to the user that Numbers.Num2 is wrong. "Input string not in correct format"
var msg = stackTrace.GetFrame(1).GetMethod().ToString();
msg = ex.Message;
msg += ex.StackTrace;
throw;
}
}
}
I'm using an extension method to convert sting to int. And i'm looking for a way to catch the wrong property in the extension method itself. I'm using .Net framework 4.0. Please suggest.
Upvotes: 0
Views: 687
Reputation: 4908
public static int StringToInt(this Numbers number,
Expression<Func<Numbers, string>> prop)
{
try
{
return Convert.ToInt32(prop.Compile()(number));
}
catch (Exception ex)
{
var expression = (MemberExpression)prop.Body;
string name = expression.Member.Name;
throw new MissingMemberException(string.Format("Invalid member {0}", name));
}
}
And call it:
var num = numbers.StringToInt(p=>p.Num1);
Upvotes: 0
Reputation: 64943
I would like to say that your code sample is very ugly since you could overcome this problem by using int.TryParse
, but as I guess you wanted to show a generalized case (bad choice) and you just want to know the caller name of the extension method: check the [CallerMemeberNameAttribute]
introduced in the 4.5 version of .NET Framework:
For example, either in an extension or regular method, do this:
public void Method([CallerMemberName] string callerName)
{
}
And the CLR will set the input parameter with the name of the caller!
Upvotes: 0
Reputation: 22008
Why not simply supply all needed data to the method during call? Schematically (you can extend it):
public static int ToInt(string number, string info)
{
try
{
// ...
}
catch(Exception e)
{
MessageBox.Show(info);
}
}
// and usage
string str1 = "123";
int n = ToInt(str1, "Trying to parsing str1");
Upvotes: 0
Reputation: 67336
I would use Int32.TryParse
instead, then you can explicitly handle the failure to parse.
public static int StringToInt(this string number)
{
try
{
int result;
if (!Int32.TryParse(number, out result))
{
// handle the parse failure
}
return result;
}
}
Upvotes: 1