gpt4 book ai didi

c# - StructureMap-服务/存储库体系结构-未在服务中捕获的异常被传递回应用程序

转载 作者:行者123 更新时间:2023-12-03 08:16:21 25 4
gpt4 key购买 nike

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

我的代码经过几层 Controller ->服务->存储库-> Nhibernate

在存储库中,违反唯一键会引发错误。我想在我的服务层中捕获此错误,因此我尝试对其进行捕获。但是,不幸的是,该错误直接通过服务层传递给了MVC。

这是我的代码示例。

首先是 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));
}

然后,我在服务中调用的方法如下所示:
    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;
}
}

nhibernate保存方法错误,而不是被服务层中的try-catch捕获,而是直接传递给MVC应用。我感觉这可能是由于我如何设置结构图。我的MVC应用程序中有所有声明。看起来是这样的:
        //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>();

我的Service类构造函数如下所示:
    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;
}

一切正常,除了错误try-catch。有什么想法我如何配置它以便服务捕获存储库错误吗?请记住,由于我的存储库是通用的,因此它可用于多种服务-在上面的代码示例中,它用于帐户服务和个人资料服务。

编辑:添加错误消息/堆栈跟踪
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

最佳答案

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

您是否已逐步检查代码以确保(例如)正确捕获并重新抛出服务中的正确异常?

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

关于c# - StructureMap-服务/存储库体系结构-未在服务中捕获的异常被传递回应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4081256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com