public (Response response, ClientIdException clientIdException, AmountException amountException, ProductException productException) Handle(Request request)
        {
            ClientIdException clientIdException = null;
            AmountException   amountException   = null;
            ProductException  productException  = null;


            if (!request.ClientId.HasValue)
            {
                clientIdException = new ClientIdException("specify client id");
            }

            if (request.Amount < 0)
            {
                amountException = new AmountException("amount < 0");
            }

            if (string.IsNullOrEmpty(request.Product))
            {
                productException = new ProductException("specify product");
            }

            //do some actions

            return(new Response {
                PolicyNumber = 10
            }, clientIdException, amountException, productException);
        }
예제 #2
0
        public async Task AddProduct_ReturnsProductCRUDResultModelWithIsSuccessfulFalse_On_ProductException()
        {
            // Arrange
            var expectedException = new ProductException("msg");

            var userManager = new Mock <IUserManager>();

            userManager.Setup(x => x.GetByUserId(It.IsAny <int>()))
            .ReturnsAsync(new User());

            var prodManager = new Mock <IProductManager>();

            prodManager.Setup(x => x.AddNewProduct(It.IsAny <Product>(), It.IsAny <RoleType>()))
            .ThrowsAsync(expectedException);

            var productService = new ProductServiceBuilder()
                                 .WithUserManager(userManager.Object)
                                 .WithProductManager(prodManager.Object)
                                 .Build();

            // Assert
            var result = await productService.AddProduct(new AddProductModel(), It.IsAny <int>());

            // Act
            Assert.False(result.IsSuccessful);
            Assert.Contains(expectedException.Message, result.Message);
        }
예제 #3
0
        /// <summary>
        /// Get a proper <see cref="HttpStatusCode"/> based on exception's details
        /// </summary>
        /// <param name="e">An exception</param>
        /// <returns>A status code</returns>
        private HttpStatusCode TranslateException(ProductException e)
        {
            if (CodeToStatusCodeMap.TryGetValue(e.Detail, out var code))
            {
                return(code);
            }

            return(HttpStatusCode.InternalServerError);
        }
예제 #4
0
 private ActionResult ProcessProductException(ProductException pex)
 {
     _logger.Error()
     .Message(pex.Message)
     .Property("productId", pex.ProductId)
     .Property("result", pex.Result)
     .Property("locator", pex.Locator)
     .Write();
     return(BadRequest($"{pex.Message}: {pex.ProductId}. {pex.Result}"));
 }
예제 #5
0
        public void Ctor2()
        {
            var e = new ProductException(0, "valid");

            Assert.That(e.ToString(), Is.EqualTo($"warning {ProductException.Prefix}0000: valid"), "ToString-1");

            e = new ProductException(9999, "valid")
            {
                FileName   = "here.cs",
                LineNumber = 42
            };
            Assert.That(e.ToString(), Is.EqualTo($"here.cs(42): warning {ProductException.Prefix}9999: valid"), "ToString-2");
        }
예제 #6
0
		void AssertThrowErrorWithCode (Action action, int code)
		{
			try {
				action ();
			}
			catch (ProductException e) {
				Assert.AreEqual (e.Code, code, $"Got code {e.Code} but expected {code}");
				return;
			}
			catch (AggregateException e) {
				Assert.AreEqual (e.InnerExceptions.Count, 1, "Got AggregateException but more than one exception");
				ProductException innerException = e.InnerExceptions[0] as ProductException;
				Assert.IsNotNull (innerException, "Got AggregateException but inner not ProductException");
				Assert.AreEqual (innerException.Code, code, $"Got code {innerException.Code} but expected {code}");
				return;
			}
			Assert.Fail ($"We should have thrown ProductException with code: {code}");
		}
예제 #7
0
        public void BadFormats()
        {
            // {0} without argument - not using the `args` overload -> no exception
            var e = new ProductException(0, true, null, "valid {0}");

            Assert.That(e.ToString(), Is.EqualTo($"error {ProductException.Prefix}0000: valid {{0}}"), "ToString-0");

            // {0} without argument
            e = new ProductException(0, true, null, "invalid {0}", null);
            Assert.That(e.ToString(), Is.EqualTo($"error {ProductException.Prefix}0000: invalid {{0}}. String.Format failed! Arguments were:. Please file an issue to report this incorrect error handling."), "ToString-1");

            // {0} with 2 arguments -> no exception
            e = new ProductException(10, "valid {0}", 1, 2);
            Assert.That(e.ToString(), Is.EqualTo($"warning {ProductException.Prefix}0010: valid 1"), "ToString-2");

            // {0} {1} with 1 argument
            e = new ProductException(10, true, new Exception("uho"), "invalid {0} {1}", 1);
            Assert.That(e.ToString(), Is.EqualTo($"error {ProductException.Prefix}0010: invalid {{0}} {{1}}. String.Format failed! Arguments were: \"1\". Please file an issue to report this incorrect error handling."), "ToString-3");
        }
예제 #8
0
        public async Task GetEditProductModel_ReturnsIsSuccessfulEqualFalse_If_CatchedProductException()
        {
            var expectedException = new ProductException("msg");

            var prodManager = new Mock <IProductManager>();

            prodManager.Setup(x => x.GetProduct(It.IsAny <int>(), It.IsAny <int>()))
            .ThrowsAsync(expectedException);

            var productService = new ProductServiceBuilder()
                                 .WithProductManager(prodManager.Object)
                                 .Build();

            // Act
            var result = await productService.GetEditProductModel(1, 1);

            // Assert
            Assert.False(result.IsSuccessful);
            Assert.Contains(expectedException.Message, result.Message);
        }
예제 #9
0
        public async Task DeleteProduct_ReturnsProductCRUDResultModelIsSuccessfulFalse_On_ProductException()
        {
            // Arrange
            var expectedException = new ProductException("msg");

            var prodManager = new Mock <IProductManager>();

            prodManager.Setup(x => x.GetProductById(It.IsAny <int>()))
            .ThrowsAsync(expectedException);

            var productService = new ProductServiceBuilder()
                                 .WithProductManager(prodManager.Object)
                                 .Build();

            // Act
            var result = await productService.DeleteProduct(1);

            // Assert
            Assert.False(result.IsSuccessful);
            Assert.Contains(expectedException.Message, result.Message);
        }
예제 #10
0
        public void Ctor5()
        {
            var e = new ProductException(0, true, null, "valid", new string [] { });

            Assert.That(e.ToString(), Is.EqualTo($"error {ProductException.Prefix}0000: valid"), "ToString-1");

            e = new ProductException(10, true, new Exception("uho"), "valid {0}", "output");
            Assert.That(e.ToString(), Is.EqualTo($"error {ProductException.Prefix}0010: valid output"), "ToString-2");

            e = new ProductException(9999, true, new NotFiniteNumberException(), "valid", new string [] { })
            {
                FileName   = "here.cs",
                LineNumber = 42
            };
            Assert.That(e.ToString(), Is.EqualTo($"here.cs(42): error {ProductException.Prefix}9999: valid"), "ToString-32");

            e = new ProductException(9999, true, new ObjectDisposedException("uho"), "valid {0}", 1)
            {
                FileName   = "there.cs",
                LineNumber = 911
            };
            Assert.That(e.ToString(), Is.EqualTo($"there.cs(911): error {ProductException.Prefix}9999: valid 1"), "ToString-4");
        }
예제 #11
0
        public void Ctor3()
        {
            var e = new ProductException(0, "valid", new string [] { });

            Assert.That(e.ToString(), Is.EqualTo($"warning {ProductException.Prefix}0000: valid"), "ToString-1");

            e = new ProductException(10, "valid {0}", "output");
            Assert.That(e.ToString(), Is.EqualTo($"warning {ProductException.Prefix}0010: valid output"), "ToString-2");

            e = new ProductException(9999, "valid", new string [] { })
            {
                FileName   = "here.cs",
                LineNumber = 42
            };
            Assert.That(e.ToString(), Is.EqualTo($"here.cs(42): warning {ProductException.Prefix}9999: valid"), "ToString-3");

            e = new ProductException(9999, "valid {0}", 1)
            {
                FileName   = "there.cs",
                LineNumber = 911
            };
            Assert.That(e.ToString(), Is.EqualTo($"there.cs(911): warning {ProductException.Prefix}9999: valid 1"), "ToString-4");
        }
예제 #12
0
        public override ActionTaskResult Process(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (context.ContentItemIds == null || context.ContentItemIds.Length == 0)
            {
                throw new ArgumentException("ContentItemIds cant be empty", "context.ContentItemIds");
            }

            UserId   = context.UserId;
            UserName = context.UserName;

            OnStartProcess();

            var exceptions = new List <ProductException>();
            int index      = 0;

            foreach (int id in context.ContentItemIds)
            {
                if (TaskContext.IsCancellationRequested)
                {
                    TaskContext.IsCancelled = true;
                    break;
                }

                try
                {
                    using (var transaction = CreateTransaction())
                    {
                        ProcessProduct(id, context.Parameters ?? new Dictionary <string, string>());
                        transaction.Commit();
                    }

                    byte progress = (byte)(++index * 100 / context.ContentItemIds.Length);
                    TaskContext.SetProgress(progress);
                }
                catch (ProductException pex)
                {
                    var logLevel = pex.IsError ? LogLevel.Error : LogLevel.Info;
                    var builder  = Logger.Log(logLevel).Message(LoggerMessage + id);
                    var result   = ActionTaskResult.FromString(pex.Message);
                    var msg      = ResourceManager.GetString(pex.Message);
                    if (result != null)
                    {
                        builder.Property("taskResult", result.ToString());
                    }
                    else if (msg != null)
                    {
                        builder.Property("taskResult", string.Format(msg, id));
                    }
                    else
                    {
                        builder.Exception(pex);
                    }
                    builder.Write();
                    exceptions.Add(pex);
                }
                catch (AggregateException aex)
                {
                    foreach (var iex in aex.InnerExceptions)
                    {
                        var ipex = iex as ProductException;

                        if (ipex == null)
                        {
                            ipex = new ProductException(id, nameof(TaskStrings.ActionErrorMessage), iex);
                        }
                        Logger.Error().Message(LoggerMessage + id).Exception(ipex).Write();
                        exceptions.Add(ipex);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error().Message(LoggerMessage + id).Exception(ex).Write();
                    exceptions.Add(new ProductException(id, nameof(TaskStrings.ServerError), ex));
                }
            }

            try
            {
                OnEndProcess();
            }
            catch (Exception ex)
            {
                exceptions.Add(new ProductException(0, "OnEndProcess error", ex));
            }

            if (exceptions.Any())
            {
                throw new ActionException(TaskStrings.ActionErrorMessage, exceptions, context);
            }

            return(null);
        }