C# System.Web.Http Filter ExceptionHandlingAttribute

Date: 2018-09-07
    public class ExceptionHandlingAttribute : ExceptionFilterAttribute
    {

        public override void OnException(HttpActionExecutedContext context)
        {
            var exception = context.Exception.GetBaseException();
            var method = context.Request.Method;
            var url = context.Request.RequestUri;
            var controllerName = context.ActionContext?.ControllerContext?.ControllerDescriptor?.ControllerName;
            var actionName = context.ActionContext?.ActionDescriptor?.ActionName;

            LoggingHelper.Logger.Error($"{method} {url}\r\n{controllerName}.{actionName}()", exception);

#if !DEBUG
            var msg = "An unhandled error occurred.";                
            string stack = null;
#else
            var msg = exception.Message;
            string stack = context.Exception.StackTrace;
#endif

            var apiError = new ApiError(msg) { Detail = stack };
            context.Response.StatusCode = HttpStatusCode.InternalServerError;
            context.Response.Content =
                new StringContent(JsonConvert.SerializeObject(apiError), Encoding.UTF8, "application/json");
        }
    }

    public class ApiError
    {
        public string Message { get; set; }
        public bool IsError { get; set; }
        public string Detail { get; set; }

        public ApiError(string message)
        {
            this.Message = message;
            IsError = true;
        }
    }

 

12580cookie-checkC# System.Web.Http Filter ExceptionHandlingAttribute