代码之家  ›  专栏  ›  技术社区  ›  Josh

StructureMap-服务/存储库体系结构-未在服务中捕获异常并将其传递回应用程序

  •  0
  • Josh  · 技术社区  · 14 年前

    我有一个对电子邮件地址有唯一限制的帐户表。

    在存储库中,当违反唯一密钥时会抛出一个错误。我想在我的服务层中捕获这个错误,所以我在它周围放置了一个尝试捕获。然而,不幸的是,这个错误是通过服务层直接抛出给MVC的。

    这是我的代码示例。

    首先是控制器:

    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));
                    }
    

    然后,我在服务中调用的方法如下所示:

        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;
            }
        }
    

            //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>();
    

    我的服务类构造函数如下所示:

        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;
        }
    

    一切正常,除了错误尝试捕获。有什么想法我如何配置它以便服务捕获存储库错误吗?请记住,因为我的存储库是通用的,所以它用于多个服务—在上面的代码示例中,它用于帐户服务和配置文件服务。

    编辑:添加错误消息/堆栈跟踪

    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
    
    2 回复  |  直到 14 年前
        1
  •  1
  •   Phil Sandler    14 年前

    我无法想象这和StructureMap有什么关系。如果容器正确地解析了您的依赖项,则容器正在执行其工作(并且您已经正确地配置了它)。

    设置一些断点,看看你对实际发生的事情是否正确。

        2
  •  1
  •   pitx3    14 年前

    我还没有足够的要点来给你的问题添加评论,所以我把它们放在这里。

    堆栈跟踪和确切的异常消息将很有帮助。我确实看到您的代码中有一点可能导致异常按原样被重新抛出:

    if (ex.Message.ToUpper().Contains("VIOLATION OF UNIQUE KEY"))
    

    异常消息是否包含该文本?