Here is a typical function that returns either true/false;
private static bool hasValue()
{
return true;
}
Now on an error, I would like to return my own custom error object with definition:
public class Failure
{
public string FailureDateTime { get; set; }
public string FailureReason { get; set; }
}
I would have expected to be able to throw this custom object for example…
private static bool hasValue()
{
try
{
// do something
}
catch
{
throw new Failure();
}
return true;
}
This is not possible, and I don’t want to derive Failure from System.IO.Exception because I have personally had issues serializing exceptions in C# (This was with .net v2).
What is the best practice / or ideal solution to this problem. Should I just work with private static object? Or is there a cleaner way to return a custom object or bypass the typical return type on an error (not using System.IO.Exception)?
I am not entirely wild about using an object either, because then I need to validate the result by using casting and more boolean.
This kind of solution may fit to this case:
You can throw the exception (recommended to define your own exception type), and use the Data dictionary to hold the Failure. In the
catchcode you can take the data and serialize it. If you do create your own exception type you can place the Failure on a property.Comment: I didn’t check it, but are you sure exceptions are not serializable?