We have the following code in our Service Layer where we add a new user to the database using EF.
public User AddUser(User user)
{
using (var context = DataObjectFactory.CreateContext())
{
var userEntity = Mapper.Map(user);
context.AddObject("UserEntities", userEntity);
context.SaveChanges();
return Mapper.Map(userEntity);
}
}
And this is called by the Service Layer via this method:
public UserResponse GetSubmitUser(UserRequest request)
{
var response = new UserResponse(request.RequestId);
var user = Mapper.FromDataTransferObject(request.User);
response.User = Mapper.ToDataTransferObject(UserDao.AddUser(user));
return response;
}
We do certain client and server validations before we reach the AddUser however I am not sure about how to handle the unhandled exception(s).
For instance if somehow context.SaveChanges() throws an error how do we bubble the error details back to the Presentation layer?
I am thinking of putting try / catch within the AddUser like this:
public User AddUser(User user)
{
try
{
using (var context = DataObjectFactory.CreateContext())
{
var userEntity = Mapper.Map(user);
context.AddObject("UserEntities", userEntity);
context.SaveChanges();
return Mapper.Map(userEntity);
}
}
catch (Exception)
{
return ??
}
}
but the return type of the AddUser is User and I'm not sure what I should be returning when an exception happens. If I can return the exception details to the UserResponse method I can populate some fields within our response object which are there to hold error details, but now sure what to return from within the catch section.
I am trying to understand how to identify exceptions that should be caught and handled in a multi layered application, one with a data access layer, service layer, presentation layer etc. Mainly trying to figure out how to surface the exception details to the user for resolution.
Thanks