有什么方法可以替换重复的try catch块吗?

时间:2019-04-26 19:59:41

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

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

我尝试使用exceptionhandler属性,但无法通过它返回状态代码或自定义消息。

是否可以替换每个函数上的try 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块以获得更好的代码。

2 个答案:

答案 0 :(得分:1)

您可以使用以下方法包装您的方法:

    /// <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

答案 1 :(得分:0)

尝试为<select multiple> <option>THIS IS A VERY LONG OPTION THIS IS A VERY LONG OPTION</option> <option>THIS IS A VERY LONG OPTION THIS IS A VERY LONG OPTION</option> <option>THIS IS A VERY LONG OPTION THIS IS A VERY LONG OPTION</option> <option>THIS IS A VERY LONG OPTION THIS IS A VERY LONG OPTION</option> <option>THIS IS A VERY LONG OPTION THIS IS A VERY LONG OPTION</option> <option>THIS IS A VERY LONG OPTION THIS IS A VERY LONG OPTION</option> </select>的{​​{1}}属性设置HttpStatusCodeResult

Result