我有一个Ria服务来调用逻辑代码。我想在每个逻辑函数中编写try catch块来提供处理unhandeled异常的方法。处理未处理的异常
try
{
//something
}
catch(BussinessException e)
{
//save e.info to database
}
但我不希望在我的逻辑到处写这个块代码,我不希望把RIA服务异常处理一件自其他类型的服务也叫逻辑。
有没有人对我有一个地方的异常处理解决方案?
我有一个Ria服务来调用逻辑代码。我想在每个逻辑函数中编写try catch块来提供处理unhandeled异常的方法。处理未处理的异常
try
{
//something
}
catch(BussinessException e)
{
//save e.info to database
}
但我不希望在我的逻辑到处写这个块代码,我不希望把RIA服务异常处理一件自其他类型的服务也叫逻辑。
有没有人对我有一个地方的异常处理解决方案?
基于你的历史,我很确定这是C#所以这里是我的看法。
避免重复的最好方法就是像这样包装你的逻辑。
private static void ExecuteLogic(Action action)
{
try
{
action();
}
catch(BussinessException e)
{
//save e.info to database
}
}
有了这个地方,你可以很容易地进行共享相同的错误处理各种操作。
ExecuteLogic(
() =>
{
// Do something...
}
);
如果您只想记录异常,就像我从您的示例中可以看到的那样,您可以订阅AppDomain.FirstChanceException。但你无法处理它。哦。顺便说一句此事件是使用命令模式更常规的面向对象解决方案引入了只在.NET 4 :(
这里
public interface ICommand {
void Execute();
}
public class BankAccountWebServiceCall: ICommand(){
string name;
int accountNo;
public BankAccountWebServiceCall(string name, int accountNo) {
this.name= param1;
this.accountNo= accountNo;
}
//ICommand implementation
public void Execute() {
SomeWebService.Call(name, accountNo);
}
}
public class WebServiceCaller {
public void CallService(ICommand command) {
try {
command.Execute();
} catch (SomeBusinessException ex) {
//handle exception
}
}
}
public class WebServiceCallerTest {
public static void CallServiceTest() {
new WebServerCaller().CallService(new TwoParameterwebServiceCall("Igor", 12345));
}
}
这是一个强有力的方法,我会用在过去,但我一直在转向一个更实用的风格与我码。 – ChaosPandion 2010-10-05 02:48:35
这是一个很好的依赖注入解决方案! – Frank 2010-10-05 15:12:23
实施IHttpModule的
web.config中:。
<httpModules>
...
<add type="Citiport.Web.Module.ErrorHandleModule" name="GlobalErrorHandler" />
...
</httpModules>
的Class:
public class ErrorHandleModule : IHttpModule
{
private static readonly ILog logger = LogManager.GetLogger("Citiport.Web.Module.ErrorHandleModule");
public ErrorHandleModule()
{
}
void IHttpModule.Dispose()
{
}
void IHttpModule.Init(HttpApplication context)
{
context.Error += new System.EventHandler(onError);
}
public void onError(object obj, EventArgs args)
{
HttpContext ctx = HttpContext.Current;
HttpResponse response = ctx.Response;
HttpRequest request = ctx.Request;
Exception exception = ctx.Server.GetLastError();
/* handling exception here*/
}
}
}
请参阅:http://code.google.com/p/citiport2/source/browse/trunk/CitiportV2_website/App_Code/Web/ErrorHandleModule.cs
。想要问一些聪明..你可以扩展IDispose这样的东西也。好主意不好主意的想法? – Kieran 2010-10-05 02:31:58
+1否则称为命令模式,很好的解决方案。 – 2010-10-05 02:32:37
@Kieran - 我相信你可以以无数种方式扩展IDisposable。你能告诉我你期望的最终目标是什么吗? – ChaosPandion 2010-10-05 02:41:46