在我的MVC WebApi服务中,当抛出异常时,它由过滤器处理:
public class GlobalExceptionFilter : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { context.Response = context.Request.CreateErrorResponse(HttpStatusCode.BadRequest,"Bad Request",context.Exception); } }
此过滤器生成的此HTTP响应取决于config.IncludeErrorDetailPolicy配置.
如果我将config.IncludeErrorDetailPolicy设置为IncludeErrorDetailPolicy.Always,则所有详细信息都会序列化为HTTP响应(Message,ExceptionMessage,ExceptionType和StackTrace).
如果我将config.IncludeErrorDetailPolicy设置为IncludeErrorDetailPolicy.Never,则仅包含Message.
但是,我想在HTTP响应中包含Message,ExceptionMessage和ExceptionType,但不包括StackTrace;如何只排除StackTrace?或者我应该将所需的详细信息连接到Message字段中?
要在我的问题中添加一些上下文,客户端需要这些异常细节来处理特殊情况……但绝不是堆栈跟踪.
解决方法
谢谢你指出我正确的方向莱昂.您的链接启发了我的解决方案.它保留CreateErrorResponse方法的功能并附加ExceptionMessage和ExceptionType属性.
public class GlobalExceptionFilter : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { context.Response = context.Request.CreateErrorResponse(HttpStatusCode.BadRequest,context.Exception); var httpError = (HttpError)((ObjectContent<HttpError>)context.Response.Content).Value; if (!httpError.ContainsKey("ExceptionType")) httpError.Add("ExceptionType",context.Exception.GetType().FullName); if (!httpError.ContainsKey("ExceptionMessage")) httpError.Add("ExceptionMessage",context.Exception.Message); } }