【问题标题】:Is there any way to replace repetitive try catch blocks?有什么方法可以替换重复的 try catch 块吗?
【发布时间】:2019-09-16 08:38:13
【问题描述】:

在我的第一个 asp.net mvc 应用程序中,我使用 try-catch 块处理错误并将特定消息作为 Httpstatuscode 返回给用户。 在每个 crud 操作中都有相同的代码块。

我尝试使用异常处理程序属性,但无法使用它返回状态代码或自定义消息。

有什么方法可以替换每个函数上的这些 try catch 块并向用户返回消息?

这是我尝试过的:

public class ExceptionHandlerFilterAttribute : FilterAttribute, IExceptionFilter
{ 
    private ILogger _logger;

    public void OnException(ExceptionContext filterContext)
    {
        _logger = new NLogLogger();
        if (!filterContext.ExceptionHandled)
        {
            var controller = filterContext.RouteData.Values["controller"].ToString();
            var action = filterContext.RouteData.Values["action"].ToString();
            var message = filterContext.Exception;

            _logger.Log(Business.Enums.LogLevel.Error, string.Concat("/",controller,"/",action), message);

            filterContext.ExceptionHandled = true;

            filterContext.Result = new ViewResult()
            {
                ViewName = "Error"
            };
        }
    }
}

这是一个示例方法:

  public HttpStatusCodeResult Create(Product product)
    {
       if (!ModelState.IsValid) return new HttpStatusCodeResult(HttpStatusCode.BadGateway);

        try
        {
            _productService.Create(product);

            return new HttpStatusCodeResult(HttpStatusCode.OK);
        }
        catch (Exception) { return new HttpStatusCodeResult(HttpStatusCode.InternalServerError); }

    }

我想替换重复的 try-catch 块以获得更好的代码。

【问题讨论】:

    标签: c# asp.net exception model-view-controller try-catch


    【解决方案1】:

    尝试为filterContextResult属性设置HttpStatusCodeResult

    filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.InternalServerError);

    【讨论】:

      【解决方案2】:

      你可以用这样的东西来包装你的方法:

          /// <summary>
          /// Tries the specified action.
          /// </summary>
          /// <param name="action">The action.</param>
          public static HttpStatusCodeResult Try(Action action, ModelState model)
          {
              if (!model.IsValid) return new HttpStatusCodeResult(HttpStatusCode.BadGateway);
              try
              {
                  action();
                  return new HttpStatusCodeResult(HttpStatusCode.OK);
              }
              catch (Exception) { return new HttpStatusCodeResult(HttpStatusCode.InternalServerError); }
          }
      

      你可以使用你的 Try:

       public HttpStatusCodeResult Create(Product product)
       {
          return Try(()=> {
              _productService.Create(product);
          }, ModelState);
       }
      

      Here an wrapper example in github

      And the call of that try

      【讨论】:

        猜你喜欢
        • 2011-08-22
        • 2011-08-20
        • 1970-01-01
        • 2012-07-17
        • 2010-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多