17,740
社区成员
发帖
与我相关
我的任务
分享
public override void OnActionExecuted
if (actionExecutedContext.Exception != null)
{
这里写就行了
public class WebApiExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
base.OnException(context);
ResultType resultType = ResultType.error;
string showMessage = string.Empty;
string errorMessage = string.Empty;
if (context.Exception is ShowInfoException)
{
resultType = ResultType.info;
}
else if (context.Exception is ShowWarningException)
{
resultType = ResultType.warning;
}
//异常消息处理
if (context.Exception is ShowException)
{
//显示类异常:在客户端提示
showMessage = context.Exception.Message;
}
else
{
//其他类Exception:优化并记录日志
ExceptionService exService = new ExceptionService();
exService.ReSolveEFException += EFExceptionService.ReSolveEFException;
errorMessage = exService.Resolve(context.Exception, "Resolve Exception").ToLower().Replace(BaseManager.ProjectPath.ToLower(), "");
string errorMessageAdd = Environment.NewLine + "日志时间: " + DateTime.Now.ToString(BaseFormat.DateTimeFormat) + Environment.NewLine + errorMessage;
var log = LogFactory.GetLogger(LogFactory.Error);
log.Error(new { errorMessage = errorMessageAdd, Exception = context.Exception });
//显示类异常:在客户端提示
if (context.Exception is CustomShowException)
{
//CustomShowException异常特殊处理,它在记入日志的同时,也要反馈到客户端
showMessage = context.Exception.Message;
}
else
{
//其他 可格式化 的系统异常:对确定性的错误进行匹配
string matchStr = ExceptionMatch.Match(errorMessage);
showMessage = matchStr != null ? matchStr : "内部服务器错误,请联系管理员。"; //无法匹配的,以简单的错误消息返回
}
}
//var response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
context.Response = new HttpResponseMessage()
{
Content = new StringContent(new AjaxResult { state = resultType.ToString(), message = showMessage }.ToJson())
};
}
}
4、将WebApiExceptionFilterAttribute 注册到全局
public static void Register(HttpConfiguration config)
{
//缺省路由
config.Routes.MapHttpRoute(
name: AppManager.AppId + "Api",
routeTemplate: "api/{controller}/{action}",
defaults: new { id = RouteParameter.Optional }
);
config.Filters.Add(new WebApiExceptionFilterAttribute());
}