I’m reading a book development of enterprise applications while working on MVC 3 project. I’m currently deciding on how to handle exceptions. Previously I would let the exception bubble up the stack and then handle it at the highest layer.
The book suggests to create an ad-hoc class in a domain model and return that. E.g.
public sealed class MissingCustomer: Customer
{
}
// On method failure return new MissingCustomer();
I can see the idea but I’m struggling to justify a need for that. Code wise I agree that it’s a lot neater to return a new missing customer, instead of throwing an exception.
What do you think about this approach and have you come across scenario where this made a significant difference?
If we assume that a customer must always exist, then it makes sense to throw an exception saying “Hey, customer should always exist and for some reason it doesn’t, so I’m going to notify user saying that something exceptional happened”. On other hand I can assume that it’s possible for a customer to be removed by another person, therefore I need to handle this gracefully.
Either way I think that we’ll need a MissingCustomer class or a MissingCustomerException as customer is a very common entity which is used throughout the system. If the view model expects a customer and we return a MissingCustomer – it’s fine as inheritance will get this working.
For example I have an action method that returns OrderViewModel. This action method requires a reference to a customer.
Customer customer = CustomerRepository.Find(10);
if(customer == null)
{
return new MissingCustomer();
}
This is going to fall over because action method will return a view model of type OrderViewModel, so now I’m more inclined towards using an exception, instead of a MissingCustomer object.
Edit
Additionally, a MissingCustomer type object would inherit properties from Customer type. These properties are not needed as the only thing we want to do, is notify users that customer can’t be found.
Thank you
I would always return
nullfrom methods used to fetch customers. By just looking at a function namedGetCustomerone would never expect that it can return a customer object which is not really a customer.It’s far better that you use something like
var customer = repos.GetCustomer(1) ?? Customer.Emptyif you can. The intent is clear and the code becomes less error prone.If your method expects to always get a customer you have failed to validate the input earlier on. Instead of creating a workaround to get the code working, try to fix it earlier on. Maybe a check to see if the customer exists?
Update
I noticed now that the question really was for your view model. It’s perfectly fine to use that kind of logic in it. The view model after all used to adapt the “M” in MVC to suit the view (and therefore remove logic from the view).
I would use