Stop displaying entire stack trace in WebAPI

When an unexpected error occurs in WebAPI the user sees the entire stack trace.

I believe that showing the entire stack trace is not safe.

What is the default behaviour to stop showing the entire trace to my users?

Just a friendly message like saying Internal Server Error alone is enough. Correct?

Any ideas how?

<?xml version="1.0"?>
<Error>
  <Message>An error has occurred.</Message>
  <ExceptionMessage>The method or operation is not implemented.</ExceptionMessage>
  <ExceptionType>System.NotImplementedException</ExceptionType>
  <StackTrace>   at MyCompany.BLL.RequirementOfService.Employee1.Employee1Service.MakeRequirementOfService(RequirementOfService RequirementOfService) in d:\Projects\MyFolder\Testing\WhiteBox\MyCompany.BAL.RequirementOfService\Employee1\Employee1Service.cs:line 37
   at MyCompany.BLL.RequirementOfService.RequirementOfServiceBLL.MakeRequirementOfService(RequirementOfService RequirementOfService) in d:\Projects\MyFolder\Testing\WhiteBox\MyCompany.BAL.RequirementOfService\RequirementOfServiceBLL.cs:line 76
   at MyCompany.RequirementOfService.Windsor.RequirementOfServiceProvider.MakeRequirementOfService(RequirementOfService RequirementOfService) in d:\Projects\MyFolder\Testing\WhiteBox\MyCompany.RequirementOfService\Windsor\RequirementOfServiceProvider.cs:line 47
   at MyCompany.RequirementOfService.RequirementOfService.Controllers.RequirementOfServiceController.Post(RequirementOfServiceDTO RequirementOfServiceDTO) in d:\Projects\MyFolder\Testing\WhiteBox\MyCompany.RequirementOfService\RequirementOfService\Controllers\RequirementOfServiceController.cs:line 87
   at lambda_method(Closure , Object , Object[] )
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.&lt;&gt;c__DisplayClass10.&lt;GetExecutor&gt;b__9(Object instance, Object[] methodParameters)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at System.Web.Http.Controllers.ApiControllerActionInvoker.&lt;InvokeActionAsyncCore&gt;d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

Upvotes: 34

Views: 19362

Answers (2)

Cesar
Cesar

Reputation: 615

For those who are looking to supress just the StackTrace and not discarding important error clues, you can implement an ExceptionFilter.

You can do this in two steps:

  1. Write your filter as below:

    using System.Web.Http.Filters;
    using System.Net;
    using System.Net.Http;
    
    public class MyExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            var request = context.Request;
            var response = request.CreateErrorResponse(HttpStatusCode.InternalServerError, context.Exception.Message);
            var content = (System.Net.Http.ObjectContent<System.Web.Http.HttpError>)response.Content;
    
            var errorValues = (System.Web.Http.HttpError)content.Value;
            errorValues["ExceptionMessage"] = context.Exception.Message;
            errorValues["ExceptionType"] = context.Exception.GetType().Name;
            if (context.ActionContext != null)
            {
                errorValues["ActionName"] = context.ActionContext.ActionDescriptor.ActionName;
                errorValues["ControllerName"] = context.ActionContext.ControllerContext.ControllerDescriptor.ControllerName;
            }
    
            context.Response = response;
        }
    }
    
  2. make the WebApi use your ExceptionFilter:

    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new MyExceptionFilterAttribute());
    

You will get this:

{
  "Message": "Your exception is here!",
  "ExceptionMessage": "Your exception is here!",
  "ExceptionType": "Exception",
  "ActionName": "MyAction",
  "ControllerName": "MyController"
}

More information at: https://learn.microsoft.com/en-us/aspnet/web-api/overview/error-handling/exception-handling

Upvotes: 11

Alireza
Alireza

Reputation: 5056

Just change configuration IncludeErrorDetailPolicy to LocalOnly and the details will not be sent to the client.

Here: http://www.asp.net/web-api/overview/extensibility/configuring-aspnet-web-api

Upvotes: 59

Related Questions