我正在做一个项目,在这个项目中,来自我的genericHandlers的大多数响应是相同的。
我们使用.NET,并通过对genericHandlers的jQuery调用请求json数据。
我们有一个返回类型,在90%的时间里使用,它类似于这样的json:{ response: { code: 0, return: myJson} },我在JavaScript中处理这个返回。
因此,每当genericHandler出现问题时,我已经有一个类来处理错误并以该格式返回它们。
我所要寻找的是避免在我们创建的每个处理程序中使用try catch的方法,并再次重复代码。
下面是"ProcessRequest“方法的一个示例:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = UContentType.Json;
try
{
// My code here
}
catch (Exception ex)
{
UError.AddMessage(ex.Message);
// Method that converts the errors into a json string
context.Response.Write(UMessage.SendErrorMessage());
}
}我需要的是将该方法包装成某种东西,以消除对每个处理程序中试图捕获的重复。
我想要使用继承之类的东西。
我在明朝的最终结果是实现了这样的目标:
public class getUser : IHttpHandlerWithExceptionTreatment // a shorter name though ;)
{
public void ProcessRequest(HttpContext context)
{
// My code here
}
public bool IsReusable
{
get
{
return false;
}
}
}如果有什么东西在那里抛出一个异常,它就会被捕获在那个扩展类或者其他什么地方。
我不知道是否可以使用设计模式(我考虑了装饰器或模板),或者只是简单的继承。我甚至不知道这是不是个好主意。:)
但我想知道这是否可能。
任何想法。
希望我对自己的怀疑很清楚。
谢谢你的帮忙
发布于 2013-11-30 02:03:10
最简单的方法可能是创建一个抽象基类:
public abstract class HandlerBase : IHttpHandler
{
bool IHttpHandler.IsReusable { get { return false; } }
void IHttpHandler.ProcessRequest(HttpContext context)
{
try
{
this.HandleRequest(context);
}
catch (Exception ex)
{
UError.AddMessage(ex.Message);
context.Response.Write(UMessage.SendErrorMessage());
}
}
protected abstract void HandleRequest(HttpContext context);
}然后让您的处理程序从HandlerBase继承而不是直接实现IHttpHandler:
public class FooHandler : HandlerBase
{
protected override void HandleRequest(HttpContext context)
{
// Handle you some Foos here
}
}https://stackoverflow.com/questions/20295140
复制相似问题