I am writing a method (for a service) that returns a specific error code to the client.
Inside this method I am calling various LINQ extension methods. Each one of these extension methods can throw exceptions of 'same' type (say InvalidOperationException), but I need to catch these exceptions individually and return a specific error code. Here is what it looks like now (much simplified version)
public errorCode SomeMethod()
{
try
{
var foo1 = SomeDataSource.Entities1.Single(x=> x.bar1 == somevalue);
}
catch(InvalidOperationException x)
{
return ErrorCode1;
}
try
{
var foo2 = SomeDataSource.Entities2.Single(x=> x.bar2 > somevalue);
}
catch(InvalidOperationException x)
{
return ErrorCode2;
}
......
This is adding up to be a lot of try-catch blocks, as there are several error conditions that can potentially exist. It is also forcing me to elevate the scope of variables like foo to outside the individual try blocks, as they are being used in subsequent try blocks.
I am just curious to see if there is a way to consolidate all this code in a more elegant manner (some inline methods perhaps?) so that it doesn't end up looking so intimidating?
Based on the feed back I got, I have to add that the Business Rules that I am trying to implement leads me to use 'Single' and not 'SingleOrDefault'. Using 'SingleOrDefault' makes it easier because then we can just check for null without catching the exception. 'Single' on the other hand simply throws an exception if the condition fails. Idea here is to consolidate all these try blocks where as somehow keep all the errors happening separate even though every call to 'Single' throws the same type of exception (InvalidOperationException)...
Thanks
You are misusing exceptions for control flow. Better:
var foo1 = SomeDataSource.Entities1.SingleOrDefault(x=> x.bar1 == somevalue);
if (foo1 == null) return ErrorCode1;
Very clean and simple.
What's especially vexing in the original code is that you are treating all occurrences of InvalidOperationException as the same thing. Who knows whether that's true or not?! There can be many things throwing this particular exception type. You might hide bugs by catching too generously. You might even hide EF bugs this way.
If you want to move your business logic into the lambda method, which it sounds like, you can do so by defining an extension.
Note: I am not endorsing the code below at all; I'm just trying to make it fit the question that you have asked.
public static class LinqExtensions
{
public static ErrorCode BusinessSingle(this IEnumerable<TSource> enumerable, Func<TSource, bool> predicate)
{
TSource result;
try
{
result = enumerable.Single(predicate);
return new NoError(); // ????
}
catch
{
return new ErrorOne();
}
}
}
But it would be far better to do one of the following:
If errors are common, then don't treat it like an Exception but rather a validation rule.
If errors are exceptional, then throw Exception that are differentiated.
You're right that if you're always expecting exactly one element to match your condition, you should use Single() rather than SingleOrDefault().
That means that if that is not the case, your system is a faulted state, and your application should shut down because it is not working correctly. By saying Single(), you're saying "I know there's exactly one there. If there's not, there's something seriously wrong."
By trying to handle the exception and return an error code instead, you're saying something different. You're saying "There should be exactly one there, but if there's not, I can do something else to handle that case." That's what SingleOrDefault() is for.
Related
I'm looking for the appropriate exception to use for each static method in a class library that I have, as all the methods are related.
public static void EnterText(string element, string value, PropertyType elementType)
{
if (PropertiesCollection.Driver == null)
{
throw new InvalidOperationException();
}
if (elementType == PropertyType.Id)
{
PropertiesCollection.Driver.FindElement(By.Id(element)).SendKeys(value);
}
else if (elementType == PropertyType.Name)
{
PropertiesCollection.Driver.FindElement(By.Name(element)).SendKeys(value);
}
else //if elementType does not make sense an argument exception is thrown
{
throw new ArgumentException();
}
}
The problem is if the PropertiesCollection.Driver is not initialized, the method is useless. Therefore, I'd like to throw an exception if it is null when the method is called. The closest thing I have found to what I'm looking for is InvalidOperationException. However MSDN says it is an "exception that is thrown when a method call is invalid for the object's current state". Since it is a static class and thus has no objects, is this an inappropriate exception type? If no, then which exception should be thrown instead?
Also on more of the organizational side of things, should the code snippet that checks if the driver is null be at the top of each method, or is that too redundant? The alternative that I can think of is a helper method called at the beginning of each that checks and throws an exception if need be.
Some people may disagree with me but saying that InvalidOperationException is the wrong exception simply because there's not technically an instance seems like hair-splitting to me. This seems like a perfectly acceptable use of this exception to me.
I suppose you could create a helper function to test for this condition and decide if you should throw the InvalidOperationException but it truthfully doesn't seem all that worthwhile, plus it could, in my opinion, actually decrease the clarity of the code. The check isn't all that much code and, if I'm reading the code, I'd prefer to just see what checks are happening rather than having to dig into another method to figure it out.
The Exception is a convenient container, that is tempting to use for various purposes. But is it OK to use it for handling legal states in your code?
My example: I have a geometric function that finds the closest object within a search radius:
public IPoint FindNearest(IPoint origin, double searchRadius)
{
}
My idea was that I could throw an exception, when the search doesn't find a hit. But is this a good idea? Alternatively, I could return Null (which I don't like), or return a result object instead of a Point.
Exception, in general, represents an invalid or "exceptional" scenario. In your case, if not finding a hit is an exceptional scenario and it should always be found in usual cases then you can throw exception.
You should always try to avoid throwing exception because of its heavy nature. If caller code is calling this method frequently and your method is in result throwing lot of exceptions, it will make your program slow
Best practice is to use exception only if you can not handle the error in a functial way. In this case not finding a location and returning null is best, because your calling function can handle the null in a functional way. Besides the clean code, throwing and handling exceptions is realy bad for performance, so use them only as last resort.
You could do something like
public bool TryFindNearest(IPoint origin, double searchRadius, out IPoint result)
{
// your logic here, return true if you find a point. Otherwise return false.
}
Then your calling code can do something like:
IPoint nearestPoint;
If (TryFindNearest(origin, searchRadius, out nearestPoint))
{
// do your stuff.
}
Exceptions should be used in invalid scenarios not to control program flow.
Usually in this situation throwing exceptions isn't a good idea, they are expensive and semantically mean something else entirely.
You could return null and do a null check, or I occasionally find that using the Special Case pattern works out nicely and makes for readable code if you give the class/interface a sensible name.
In this instance, you'd return either an implementing class or derived interface called something like:
public class NoHitOnRadius : IPoint {}
And return that from the call when you get no hits. Then the calling code checks the return type:
var p = FindNearest(...);
if (p is NoHitOnRadius)
{
// Do something.
}
Although in this specific situation I'd likely go with the TryFindNearest semantics (to keep commonality with the likes of TryParse etc) that RobH suggests.
This is not so much of a problem but more feedback and thoughts. I have been considering an implementation for methods that have been tested thoroughly through our internal teams. I would like to write a generic exception catch method and reporting service.
I relize this is not as easy as a "try-catch" block, but allows for a uniform method for catching exceptions. Ideally I would like to execute a method, provide a failure callback and log all the parameters from the calling method.
Generic Try-Execute.
public class ExceptionHelper
{
public static T TryExecute<T, TArgs>(Func<TArgs, T> Method, Func<TArgs, T> FailureCallBack, TArgs Args)
{
try
{
return Method(Args);
}
catch (Exception ex)
{
StackTrace stackTrace = new StackTrace();
string method = "Unknown Method";
if (stackTrace != null && stackTrace.FrameCount > 0)
{
var methodInfo = stackTrace.GetFrame(1).GetMethod();
if (methodInfo != null)
method = string.Join(".", methodInfo.ReflectedType.Namespace, methodInfo.ReflectedType.Name, methodInfo.Name);
}
List<string> aStr = new List<string>();
foreach (var prop in typeof(TArgs).GetProperties().Where(x => x.CanRead && x.CanWrite))
{
object propVal = null;
try
{
propVal = prop.GetValue(Args, null);
}
catch
{
propVal = string.Empty;
}
aStr.Add(string.Format("{0}:{1}", prop.Name, propVal.ToString()));
}
string failureString = string.Format("The method '{0}' failed. {1}", method, string.Join(", ", aStr));
//TODO: Log To Internal error system
try
{
return FailureCallBack(Args);
}
catch
{
return default(T);
}
}
}
}
What I know as draw backs.
Performance Loss using reflection
MethodBase (methodInfo) may not be available through optimization
The try-catch around the error handler. Basically I could use the TryExecute wrapper for the try-catch around the error call back however that could result in a stack overflow situation.
Here would be a sample implementation
var model = new { ModelA = "A", ModelB = "B" };
return ExceptionHelper.TryExecute((Model) =>
{
throw new Exception("Testing exception handler");
},
(Model) =>
{
return false;
},
model);
Thoughts and comments appreciated.
That's a lot of code to put in a catch, including two more try/catch blocks. Seems like a bit of overkill if you ask me, with a good amount of risk that a further exception can obscure the actual exception and that the error information would be lost.
Also, why return default(T)? Returning defaults or nulls as indications of a problem is usually pretty sloppy. If nothing else, it requires the same conditional to be wrapped around every call to the method to check for the return and respond to... some error that has gone somewhere else now.
Honestly, that usage example looks pretty messy, too. It looks like you'll end up obscuring the actual business logic with the error-trapping code. The entire codebase will look like a series of error traps, with actual business logic hidden somewhere in the entanglement of it. This takes valuable focus off of the actual intent of the application and puts something of background infrastructure importance (logging) at the forefront.
Simplify.
If an exception occurs within a method, you generally have two sensible options:
Catch (and meaningfully handle) the exception within the method.
Let the exception bubble up the stack to be caught elsewhere.
There's absolutely nothing wrong with an exception escaping the scope of the method in which it occurs. Indeed, exceptions are designed to do exactly that, carrying with them useful stack information about what happened and where. (And, if you add meaningful runtime context to the exception, it can also carry information about why.)
In fact, the compiler even subtly hints at this. Take these two methods for example:
public int Sum(int first, int second)
{
// TODO: Implement this method
}
public int Product(int first, int second)
{
throw new NotImplementedException();
}
One of these methods will compile, one of them will not. The compiler error will state that not all code paths return a value on the former method. But why not the latter? Because throwing an exception is a perfectly acceptable exit strategy for a method. It's how the method gives up on what it's doing (the one thing it should be trying to do and nothing more) and let's the calling code deal with the problem.
The code should read in a way that clearly expresses the business concept being modeled. Error handling is an important infrastructure concept, but it's just that... infrastructure. The code should practically scream the business concept being modeled, clearly and succinctly. Infrastructure concerns shouldn't get in the way of that.
This is very rarely going to be useful.
It covers only cases where:
The method has a well-defined means of obtaining an appropriate return value in the face of failure.
You'd actually care to log that it happened.
Now, 2 is very common with exceptions of all sorts, but not where 1 is true too.
1 of course is rare, since in most cases if you could produce a reasonable return value for given parameters by means X you wouldn't be trying means Y first.
It also has a default behaviour of returning default(T) - so null or all zeros - if the fallback doesn't work.
This only works where your case 1 above has "something that just returns null as a result because we don't really care very much what this thing does", or where the called method never returns null, in which case you then test for null, which means that your real error-handling code happens there.
In all, what you've got here is a way in which exceptions that would be trappable by real code have to be caught for by testing (and sometimes testing + guesswork) instead, and those that would bring down a program in a clear place with nice debugging information will instead put it into a state where you don't know what's going on anywhere, but at least of the few dozen bugs that got logged before something managed to bring it down fully, one of the is probably the actual problem
When you've a catch on some exception for a particular reason, by all means log the exception. Note that this is not so much to help find bugs (if that exception being raised there is a bug, you shouldn't be catching it there), but to cancel out the fact that having a catch there could hide bugs - i.e. to cancel out the very effect you are deliberately encouraging by putting catches all over the place. (E.g. you expect a regularly hit webservice to fail to connect on occasion, and you can go on for some hours with cached data - so you catch the failure and go on from cache - here you log because if there was a bug meaning you were never trying to hit the webservice correctly, you've just hidden it).
It's also reasonable to have some non-interactive (service or server) app log all exceptions that reach the top of the stack, because there's nobody there to note the exception.
But exceptions are not the enemy, they're the messenger. Don't shoot the messenger.
I have a Result object that lets me pass around a List of event messages and I can check whether an action was successful or not.
I've realized I've written this code in alot of places
Result result;
try
{
//Do Something
...
//New result is automatically a success for not having any errors in it
result = new Result();
}
catch (Exception exception)
{
//Extension method that returns a Result from the exception
result = exception.ToResult();
}
if(result.Success) ....
What I'm considering is replacing this usage with
public static Result CatchException(Action action)
{
try
{
action();
return new Result();
}
catch (Exception exception)
{
return exception.ToResult();
}
}
And then use it like
var result = Result.CatchException(() => _model.Save(something));
Does anyone feel there's anything wrong with this or that I'm trading reusability for obscurity?
Edit: The reason I am trapping all exceptions is I use this code inside of my ViewPresenter classes at any point I interact with my model since if I get an unhandled exception I'd rather display the actual error to the user (internal app) as opposed to just redirecting them the generic error page.
I don't think there is anything wrong with using a functional approach, and passing in a lambda. That is perfectly valid.
That being said, I'd question your use in this specific scenario. Trapping all exceptions into a general purpose "Result" class seems dangerous. Ideally, you should be catching exceptions which you can handle correctly - not every possible exception and continuing.
That being said, if you really want to do this, I have a couple of suggestions for you:
1) I'd make a static, immutable result for success, and just do:
result = result.Success;
This avoids generating a new "success" each time you succeed, which hopefully is the most common option.
2) I'd probably avoid the extension method, and do:
result = new Result(exception);
This will be much more clear and obvious in intent, and there's really no reason to do an extension method in this case...
You shouldn't be catching Exception like this. You should only be catching known exception types that you know how to handle.
If you did that, you code would no longer be so repetitive, so there would be no case for using this pattern for re-usability.
All round this looks like a very bad idea, not just the lambda pattern, I'm talking about the handling of exceptions by converting them into results objects. You are basically allowing yourself to ignore all exceptions and continue working. There is a reason why C# error handling is done with exceptions and not with return codes, and that is because exceptions allow for structured, hierarchical and call stack based handling. Unless you have simplified the code for this question, I would reconsider your exception handling process.
In general though, I don't see anything wrong with the lambda pattern. I use something similar myself for wrapping multiple retries of a code block. But in this case I don't think it's what you need.
If you feel the need to write such an automated exception handler system you may be over-using exceptions, which could have serious performance implications.
However, this appears to be a generic system for converting exceptions into error codes - so why not just use error codes in the first place? Or learn to use exceptions more effectively so you don't feel the need to convert them into error codes? The fact that you are trying to convert them to something else should raise alarms and suggest to you that you're missing the point somewhere.
There are certain areas in your code that you don't want the program execution to stop, like say during a checkout at a ecomm store.
I was thinking of creating a special 'return' type that looks like:
public bool SpecialReturn
{
public bool IsSucess {get;set;}
public List Messages {get;set;}
}
I could put an enum there to return a ReturnType etc. if I wanted.
Point being, I would then, call my CheckOut process method and return this, so I could then handle the error more gracefully.
is this a good practice?
Program execution doesn't have to stop when you hit an exception.
In general I would recommend throwing an exception when things go wrong. If you don't want that exception to bring down the program then catch it and handle it gracefully.
Of course, there are always situations where returning some sort of status object might be a better idea than throwing/catching exceptions, and your situation might be one of those, but without more information it's difficult to say.
you come from the wonderful world of C don't you?
yes, you can do that. but it wouldn't be useful...
your code can still throw from the ClassLibrery
and handling error codes, well sucks...
throwing exceptions don't stop the program, they just inform the upper level of an unexpected error... try...catch...
you should use exceptions, but well only in exceptional circumstances...
is this a good practice?
I'd say NOT.
Create your own subclass of Exception, add your custom properties as required (to report context info relevant to your needs) and throw.
If you use Visual Studio, there is a good code snippet for that, called Exception.
[Serializable]
public class MyCustomException : Exception
{
public MyCustomException(string myMessage)
{
MyMessage = myMessage;
}
protected MyCustomException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
public string MyMessage { get; private set; }
}
//...
throw new MyCustomException("Hello, world!");
If a function can succeed and return a result, or fail and not return a result you could use the same pattern that Microsoft does in a number of places. TryParse being a perfect example.
int result;
if ( Int32.TryParse("MyStringMayFail", out result) )
{
// Succeeded result is usable
}
else
{
// failed result is undefined and should not be trusted.
}
The actual return type of the method indicates success or failure, a parametrised out variable holds the 'result' of any operation the function may be performing. This style of coding enables the end user of the function to code directly on the success or failure of the function.
It is dead easy to create your own implementation of the TryParse methods, they are usually coupled with Parse methods which throw exceptions if something fails during processing.
If it is in fact an 'exceptional' case, and not just a valid failure, it is perfectly reasonable to throw an exception. In your case, you can handle the exception, and continue execution as best you can.
In the end what you are proposing is just recreating what exception handling already accomplishes for you.
Now if the failure is due to a credit card authorization failure (meaning invalid card number, connection failure would require an exception) or something like that. I would use failure codes, and error messages instead of exceptions.