Reputation: 51063
I have a Service layer in my MVC3 app, which plays the role of a Repository among other things, as a layer between my Data layer and the actual web application. I have coded all my GetById
methods to be robust, using FirstOrDefault
and not just First, because the Id is passed in a URL and cannot be guaranteed to be a valid Id.
I now find myself where I'm doing a FirstOrDefault
, then only proceeding if the result is not null. I would like to log the event when it is null, and then proceed to do nothing etc. Now, I am already using Elmah to log unhandled exceptions, and I have very little experience with exception handling etc. in MVC3, but it occurs to me that it might be better for me to use a simple First
, with Elmah logging the exception if no entity is found.
How should I approach this scenario, where an invalid Id is quite definitely an logic exception, but not a low level CLR exception? This is not like when somebody is asked to enter an Id and no entity is found for their search term, which is a normal logic result.
Upvotes: 1
Views: 448
Reputation: 2563
Generating exceptions can be expensive. You're initial approach of validating user input is more robust. I would recommend using a logging framework such as NLog (http://nlog-project.org) to log the case were an invalid ID is passed in.
If you would like to keep all of your log messages in Elmah, then you can decide to write directly to Elmah's error log instead of bubbling-up an exception.
Upvotes: 1