[英]Is there any way to replace repetitive try catch blocks?
在我的第一個asp.net mvc應用程序中,我正在使用try-catch塊處理錯誤,並將特定消息作為Httpstatuscode返回給用戶。 在每個粗體操作中,都有相同的代碼塊。
我嘗試使用exceptionhandler屬性,但是無法使用它返回狀態代碼或自定義消息。
有什么方法可以替換每個函數上的這些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塊以獲得更好的代碼。
您可以使用以下方法包裝方法:
/// <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);
}
嘗試設置HttpStatusCodeResult
為Result
的屬性filterContext
:
filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.