I have an account table with a unique constraint on the e-mail address.
My code travels through several layers Controller -> Service -> Repository -> Nhibernate
Inside the repository, an error is thrown when the unique key is violated. I want to catch this error in my service layer, so I put a try catch around it. Unfortunately, however, the error is throw up past the service layer directly to MVC.
Here's my code samples.
First the controller:
NewAccountRequest request = new NewAccountRequest()
{
EmailAddress = model.EmailAddress,
FirstName = model.FirstName,
LastName = model.LastName,
Password = model.Password
};
try
{
accountService.RegisterAccount(request);
//send the user off to recieve their activation e-mail
return RedirectToAction("SendActivation", new { id = model.EmailAddress });
}
catch (EmailAlreadyRegisteredException)
{
ModelState.AddModelError("EmailAddress", String.Format("The email address {0} is already registered. <a href=\"/SignIn\">Sign In</a>", model.EmailAddress));
}
Then, the method I am calling in the service looks like this:
public void RegisterAccount(NewAccountRequest request)
{
Account account = new Account()
{
EmailAddress = request.EmailAddress,
Password = request.Password
};
Profile profile = new Profile()
{
EmailAddress = request.EmailAddress,
Name = new Profile.ProfileName() { FirstName = request.FirstName, LastName = request.LastName }
};
try
{
accountRepository.SaveWithDependence<Profile>(account, profile);
}
catch (System.Data.SqlClient.SqlException ex)
{
if (ex.Message.ToUpper().Contains("VIOLATION OF UNIQUE KEY"))
throw new EmailAlreadyRegisteredException();
else
throw;
}
catch (Exception ex)
{
if (ex.Message.ToUpper().Contains("VIOLATION OF UNIQUE KEY"))
throw new EmailAlreadyRegisteredException();
else
throw;
}
}
The nhibernate save method errors and instead of being trapped by the try-catch in the service layer, it is passed directly up to the MVC app. I have a feeling this may be due to how I set up structuremap. I have all declarations in my MVC app. Here's how that looks:
//repository registration
For(typeof(MySite.Data.IRepository<>)).Singleton().Use(typeof(MySite.Infrastructure.Repository<>));
//services
For<MySite.Services.IEmailService>().Singleton().Use<MySite.Services.Impl.BasicEmailService>()
.Ctor<string>("activationUrlFormat").Is(ConfigurationHelper.UrlFormats.ActivationLink) //{0} is the email address, {1} is the HMAC
.Ctor<string>("passwordResetUrlFormat").Is(ConfigurationHelper.UrlFormats.ResetPasswordLink); //{0} is the email address, {1} is the HMAC
For<MySite.Services.IAccountService>().Singleton().Use<MySite.Services.Impl.AccountService>()
.Ctor<int>("activationLinkLifeSpan").Is(ConfigurationHelper.Defaults.ActivationLinkLifespan) //In hours
.Ctor<int>("passwordResetLinkLifeSpan").Is(ConfigurationHelper.Defaults.ResetPasswordLinkLifespan); //In hours
For<MySite.Services.IProfileService>().Singleton().Use<MySite.Services.Impl.ProfileService>();
My Service class constructor looks like this:
IRepository<Account> accountRepository;
IRepository<Profile> profileRepository;
IEmailService emailService;
int activationLinkLifeSpan;
int passwordResetLinkLifeSpan;
public AccountService(IRepository<Account> accountRepository, IRepository<Profile> profileRepository, IEmailService emailService,
int activationLinkLifeSpan, int passwordResetLinkLifeSpan)
{
this.accountRepository = accountRepository;
this.profileRepository = profileRepository;
this.emailService = emailService;
this.activationLinkLifeSpan = activationLinkLifeSpan;
this.passwordResetLinkLifeSpan = passwordResetLinkLifeSpan;
}
everything works, except the error try-catch. Any ideas how I configure this so the service catches the repository errors? Keep in mind that because my repository is generic, it is used in multiple services - in the code sample above it's used in the account service and profile service.
EDIT: Adding the error message/stack trace
Violation of UNIQUE KEY constraint 'U_Email'. Cannot insert duplicate key in object 'dbo.WebAccounts'.
The statement has been terminated.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Violation of UNIQUE KEY constraint 'U_Email'. Cannot insert duplicate key in object 'dbo.WebAccounts'.
The statement has been terminated.
Source Error:
Line 81: using (ITransaction tx = Session.BeginTransaction())
Line 82: {
Line 83: Session.SaveOrUpdate(entity);
Line 84: Session.SaveOrUpdate(dependant);
Line 85: tx.Commit();
Source File: C:\Users\Josh\Documents\Visual Studio 2010\Projects\MySite.Web\MySite.Infrastructure\Repository.cs Line: 83
Stack Trace:
[SqlException (0x80131904): Violation of UNIQUE KEY constraint 'U_Email'. Cannot insert duplicate key in object 'dbo.WebAccounts'.
The statement has been terminated.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +2030802
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +5009584
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +234
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2275
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +33
System.Data.SqlClient.SqlDataReader.get_MetaData() +86
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +311
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +987
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +162
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12
System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader() +12
NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd) +278
NHibernate.Id.InsertSelectDelegate.ExecuteAndExtract(IDbCommand insert, ISessionImplementor session) +52
NHibernate.Id.Insert.AbstractReturningDelegate.PerformInsert(SqlCommandInfo insertSQL, ISessionImplementor session, IBinder binder) +83
[GenericADOException: could not insert: [MySite.Core.Model.Account][SQL: INSERT INTO WebAccounts (EmailAddress, IsActivated, Password) VALUES (?, ?, ?); select SCOPE_IDENTITY()]]
NHibernate.Id.Insert.AbstractReturningDelegate.PerformInsert(SqlCommandInfo insertSQL, ISessionImplementor session, IBinder binder) +226
NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[] fields, Boolean[] notNull, SqlCommandInfo sql, Object obj, ISessionImplementor session) +204
NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[] fields, Object obj, ISessionImplementor session) +184
NHibernate.Action.EntityIdentityInsertAction.Execute() +150
NHibernate.Engine.ActionQueue.Execute(IExecutable executable) +117
NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate(Object entity, EntityKey key, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess) +502
NHibernate.Event.Default.AbstractSaveEventListener.PerformSave(Object entity, Object id,开发者_如何学编程 IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess) +323
NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess) +130
NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event) +27
NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event) +63
NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.PerformSaveOrUpdate(SaveOrUpdateEvent event) +89
NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event) +191
NHibernate.Impl.SessionImpl.FireSaveOrUpdate(SaveOrUpdateEvent event) +260
NHibernate.Impl.SessionImpl.SaveOrUpdate(Object obj) +256
MySite.Infrastructure.Repository`1.SaveWithDependence(T entity, K dependant) in C:\Users\Josh\Documents\Visual Studio 2010\Projects\MySite.Web\MySite.Infrastructure\Repository.cs:83
MySite.Services.Impl.AccountService.RegisterAccount(NewAccountRequest request) in C:\Users\Josh\Documents\Visual Studio 2010\Projects\MySite.Web\MySite.Services\Impl\AccountService.cs:50
MySite.Web.Controllers.RegisterController.Index(NewUserRegistrationModel model) in C:\Users\Josh\Documents\Visual Studio 2010\Projects\MySite.Web\MySite.Web\Controllers\RegisterController.cs:66
lambda_method(Closure , ControllerBase , Object[] ) +108
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +51
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +409
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +52
System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +127
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +436
System.Web.Mvc.<>c__DisplayClassf.<InvokeActionMethodWithFilters>b__c() +61
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +436
System.Web.Mvc.<>c__DisplayClassf.<InvokeActionMethodWithFilters>b__c() +61
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +436
System.Web.Mvc.<>c__DisplayClassf.<InvokeActionMethodWithFilters>b__c() +61
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +436
System.Web.Mvc.<>c__DisplayClassf.<InvokeActionMethodWithFilters>b__c() +61
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +305
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830
System.Web.Mvc.Controller.ExecuteCore() +136
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +65
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8841105
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
I can't imagine this having anything to do with StructureMap. If your dependencies are correctly resolved by the container, the container is doing its job (and you've got it configured correctly).
Have you stepped through the code to ensure that (for example) you are correctly catching and re-throwing the right exception in the service?
Set some breakpoints and see if you're right about what is actually happening.
I don't have enough points yet to add comments to your question so I'll put them here.
A stack trace and the exact exception message would be helpful. I do see one point in your code that could be causing your exceptions to be rethrown as-is is:
if (ex.Message.ToUpper().Contains("VIOLATION OF UNIQUE KEY"))
Does the exception message actually contain that text?
精彩评论