/// <summary> /// Handles the exception. /// </summary> /// <param name="context">The context.</param> /// <param name="exception">The exception.</param> /// <returns></returns> private static Task HandleException(HttpContext context, Exception exception) { context.Response.ContentType = "application/json"; if (exception is ArgumentException) { context.Response.StatusCode = StatusCodes.Status400BadRequest; } else if (exception is UnauthorizedAccessException) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; } else if (exception is NotImplementedException) { context.Response.StatusCode = StatusCodes.Status501NotImplemented; } else { context.Response.StatusCode = StatusCodes.Status500InternalServerError; } var jsonResult = ControllerExtensions.ConstructJsonError(CollectMessages(exception)); var response = JsonConvert.SerializeObject(jsonResult.Value, jsonResult.SerializerSettings); return(context.Response.WriteAsync(response)); }