Error information without a stack trace

In my MVC WebApi service, when an exception is thrown, it is handled by a filter:

public class GlobalExceptionFilter : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { context.Response = context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Bad Request", context.Exception); } } 

This HTTP response generated by this filter depends on the configuration of config.IncludeErrorDetailPolicy.

If I set config.IncludeErrorDetailPolicy to IncludeErrorDetailPolicy.Always , all details are serialized in an HTTP response ( Message , ExceptionMessage , ExceptionType and StackTrace ).

If I set config.IncludeErrorDetailPolicy to IncludeErrorDetailPolicy.Never , only Message included.

However, I want to include Message , ExceptionMessage and ExceptionType in the HTTP response, but not StackTrace ; How can I exclude only StackTrace ? Or should I just concatenate the necessary data in the Message field?

To add some context to my question, the client needs these exception details to handle special cases ... but never a stack trace.

+5
source share
2 answers

Thank you for pointing me in the right direction Leon. Your link inspired my decision below. It retains the functionality of the CreateErrorResponse method and adds ExceptionMessage and ExceptionType attributes.

 public class GlobalExceptionFilter : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { context.Response = context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Bad Request", context.Exception); var httpError = (HttpError)((ObjectContent<HttpError>)context.Response.Content).Value; if (!httpError.ContainsKey("ExceptionType")) httpError.Add("ExceptionType", exception.GetType().FullName); if (!httpError.ContainsKey("ExceptionMessage")) httpError.Add("ExceptionMessage", exception.Message); } } 
+6
source

Concatenation: no

Cancel and expand: yes

Take a look at the accepted answer here: Return custom error objects to the web API

and more info (in general) here: Throw HttpResponseException or return Request.CreateErrorResponse?

+1
source

Source: https://habr.com/ru/post/1208629/


All Articles