Esempio n. 1
0
        private static async Task HandleExceptionAsync(HttpContext context, Exception error)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = error switch
            {
                NotFoundException e => (int)HttpStatusCode.NotFound,
                BusinessException e => (int)HttpStatusCode.UnprocessableEntity,
                TokenNotInformated e => (int)HttpStatusCode.BadRequest,
                ValidationException e => (int)HttpStatusCode.BadRequest,
                ForbiddenException e => (int)HttpStatusCode.Forbidden,
                ListStringException e => (int)HttpStatusCode.UnprocessableEntity,
                AlreadyExistsException e => (int)HttpStatusCode.Conflict,
                _ => (int)HttpStatusCode.InternalServerError
            };

            var lstStringExption = new ListStringException();

            if (typeof(ListStringException) == error.GetType())
            {
                lstStringExption = (ListStringException)error;
            }

            var result = JsonSerializer.Serialize(new
            {
                message = (lstStringExption.TaskExceptions.Any()) ? "Houve um erro." : error?.Message,
                errors  = lstStringExption.TaskExceptions.Select(c => c.Message.ToString())
            });

            await context.Response.WriteAsync(result);
        }
    }
Esempio n. 2
0
        internal static IActionResult ErrorResult <TModel>(BaseException exception)
        {
            switch (exception)
            {
            case ForbiddenException _:
            case NotFoundException _:
            case UnauthorizedException _:
                LogWarning <TModel>("A warning has occurred.", exception);
                break;

            default:
                LogError <TModel>("An error has occurred.", exception);
                break;
            }

            var @try = HandleException <TModel>(exception);

            return(@try.Match(
                       failure => failure switch
            {
                InvalidRequestException _ => new BadRequestObjectResult(@try),
                ForbiddenException _ => new ObjectResult(@try)
                {
                    StatusCode = 403
                },
                NotFoundException _ => new NotFoundObjectResult(@try),
                AlreadyExistsException _ => new ConflictObjectResult(@try),
                UnauthorizedException _ => new UnauthorizedObjectResult(@try),
                InvalidObjectException _ => new UnprocessableEntityObjectResult(@try),
                _ => new ObjectResult(@try)
                {
                    StatusCode = 500
                },
            },
Esempio n. 3
0
        /// <summary>
        ///    创建一个HBase表
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="descriptors">表描述符</param>
        /// <returns>如果创建成功,则返回可以操作该表的实例</returns>
        /// <exception cref="AlreadyExistsException">表已经存在</exception>
        /// <exception cref="IOErrorException">IO错误</exception>
        /// <exception cref="IllegalArgumentException">参数错误</exception>
        /// <exception cref="ArgumentNullException">参数不能为空</exception>
        /// <exception cref="CommunicationTimeoutException">通信超时</exception>
        /// <exception cref="CommunicationFailException">通信失败</exception>
        /// <exception cref="NoConnectionException">内部无任何可用的远程连接异常,这通常代表无法连接到任何一台远程服务器</exception>
        public IHTable CreateTable(string tableName, params ColumnDescriptor[] descriptors)
        {
            if (string.IsNullOrEmpty(tableName))
            {
                throw new ArgumentNullException("tableName");
            }
            if (descriptors == null || descriptors.Length == 0)
            {
                throw new ArgumentNullException("descriptors");
            }
            IThriftConnectionAgent agent = _connectionPool.GetChannel(_regionServers[0], "RegionServer", _protocolStack, _transactionManager);

            if (agent == null)
            {
                throw new NoConnectionException();
            }
            Exception ex = null;
            ThriftMessageTransaction transaction    = agent.CreateTransaction();
            AutoResetEvent           autoResetEvent = new AutoResetEvent(false);

            transaction.ResponseArrived += delegate(object sender, LightSingleArgEventArgs <ThriftMessage> e)
            {
                CreateTableResponseMessage rspMsg = (CreateTableResponseMessage)e.Target;
                if (rspMsg.IOErrorMessage != null)
                {
                    ex = new IOErrorException(rspMsg.IOErrorMessage.Reason);
                }
                else if (rspMsg.IllegalArgumentErrorMessage != null)
                {
                    ex = new IllegalArgumentException(rspMsg.IllegalArgumentErrorMessage.Reason);
                }
                else if (rspMsg.AlreadyExistsErrorMessage != null)
                {
                    ex = new AlreadyExistsException(rspMsg.AlreadyExistsErrorMessage.Reason);
                }
                autoResetEvent.Set();
            };
            transaction.Timeout += delegate
            {
                ex = new CommunicationTimeoutException(transaction.SequenceId);
                autoResetEvent.Set();
            };
            transaction.Failed += delegate
            {
                ex = new CommunicationFailException(transaction.SequenceId);
                autoResetEvent.Set();
            };
            CreateTableRequestMessage reqMsg = new CreateTableRequestMessage {
                TableName = tableName, ColumnFamilies = descriptors
            };

            transaction.SendRequest(reqMsg);
            autoResetEvent.WaitOne();
            if (ex != null)
            {
                throw ex;
            }
            return(new HTable(reqMsg.TableName, this, _hostMappingManager));
        }
Esempio n. 4
0
 public static void ThrowIfDuplicateKey(this MongoWriteException ex, string fieldKey, string errorMessage)
 {
     if (ex.WriteError != null && ex.WriteError.Category == ServerErrorCategory.DuplicateKey && ex.WriteError.Code == 11000)
     {
         var alreadyExistsException = new AlreadyExistsException();
         alreadyExistsException.AddModelError(fieldKey, errorMessage);
         throw alreadyExistsException;
     }
 }
        public void WhenCallEdit_AndTheCommandIsSave_AndThrowAlreadyExistsException_TheShouldReturnEditViewWithModelStateInvalid()
        {
            // Arrange
            var clientInputModel       = CreateClientModel("1", "secret").ToInputModel();
            var alreadyExistsException = new AlreadyExistsException();

            alreadyExistsException.AddModelError("someKey", "someMessage");

            ClientServiceMock.Setup(service => service.UpsertClientAsync(It.IsAny <ClientInputModel>())).Throws(alreadyExistsException);

            // Act
            var actionResult      = ClientController.Edit(clientInputModel, ControllerConstants.SAVE, string.Empty).GetAwaiter().GetResult() as ViewResult;
            var actionResultModel = actionResult?.Model as ClientInputModel;

            // Assert
            Assert.IsFalse(ClientController.ModelState.IsValid);
            Assert.IsNotNull(actionResult);
            Assert.AreEqual(clientInputModel, actionResultModel);
        }
        public void TestExceptions()
        {
            {
                AlreadyExistsException v1 = new AlreadyExistsException("ex");
                AlreadyExistsException v2 = (AlreadyExistsException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                ConfigurationException v1 = new ConfigurationException("ex");
                ConfigurationException v2 = (ConfigurationException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                ConnectionBrokenException v1 = new ConnectionBrokenException("ex");
                ConnectionBrokenException v2 = (ConnectionBrokenException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                ConnectionFailedException v1 = new ConnectionFailedException("ex");
                ConnectionFailedException v2 = (ConnectionFailedException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                ConnectorException v1 = new ConnectorException("ex");
                ConnectorException v2 = (ConnectorException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }
            {
                ConnectorIOException v1 = new ConnectorIOException("ex");
                ConnectorIOException v2 = (ConnectorIOException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }
            {
                ConnectorSecurityException v1 = new ConnectorSecurityException("ex");
                ConnectorSecurityException v2 = (ConnectorSecurityException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                InvalidCredentialException v1 = new InvalidCredentialException("ex");
                InvalidCredentialException v2 = (InvalidCredentialException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                InvalidPasswordException v1 = new InvalidPasswordException("ex");
                InvalidPasswordException v2 = (InvalidPasswordException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                PasswordExpiredException v1 = new PasswordExpiredException("ex");
                v1.Uid = (new Uid("myuid"));
                PasswordExpiredException v2 = (PasswordExpiredException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
                Assert.AreEqual("myuid", v2.Uid.GetUidValue());
            }

            {
                OperationTimeoutException v1 = new OperationTimeoutException("ex");
                OperationTimeoutException v2 = (OperationTimeoutException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                PermissionDeniedException v1 = new PermissionDeniedException("ex");
                PermissionDeniedException v2 = (PermissionDeniedException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                UnknownUidException v1 = new UnknownUidException("ex");
                UnknownUidException v2 = (UnknownUidException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                ArgumentException v1 = new ArgumentException("my msg");
                ArgumentException v2 = (ArgumentException)CloneObject(v1);
                Assert.AreEqual("my msg", v2.Message);
            }

            {
                ArgumentNullException v1 = new ArgumentNullException(null, "my msg 1");
                ArgumentException     v2 = (ArgumentException)CloneObject(v1);
                Assert.AreEqual("my msg 1", v2.Message);
            }

            {
                Exception v1 = new Exception("my msg2");
                Exception v2 = (Exception)CloneObject(v1);
                Assert.AreEqual("my msg2", v2.Message);
            }
        }
Esempio n. 7
0
 private HttpErrorModel DefineHttpError(Exception exception)
 {
     return(exception switch
     {
         SignInException _ => new HttpErrorModel
         {
             Details = new HttpErrorModel.ErrorDetails
             {
                 Text = "Неверный логин / пароль!"
             },
             StatusCode = 400
         },
         IdentityUserException identityUserExc => new HttpErrorModel
         {
             Details = new HttpErrorModel.ErrorDetails
             {
                 Text = identityUserExc.Description,
                 Details = identityUserExc.Errors
             },
             StatusCode = 409,
             NeedToLog = Regex.Matches(identityUserExc.Description, @"\p{IsBasicLatin}").Count > 0
         },
         AlreadyExistsException alrExistsExc => new HttpErrorModel
         {
             Details = new HttpErrorModel.ErrorDetails
             {
                 Text = alrExistsExc.ParamName == null
                     ? $"{alrExistsExc.Message} уже существует!"
                     : $"{alrExistsExc.Message} с такми {alrExistsExc.ParamName} уже существует!"
             },
             StatusCode = 400
         },
         NotFoundException notFoundExc => new HttpErrorModel
         {
             Details = new HttpErrorModel.ErrorDetails
             {
                 Text = notFoundExc.Description
             },
             StatusCode = 404
         },
         MissingParametersException missParamsExc => new HttpErrorModel
         {
             Details = new HttpErrorModel.ErrorDetails
             {
                 Text = "Необходимо заполнить все поля!",
                 Details = missParamsExc.MissingParameters
             },
             StatusCode = 400
         },
         AccessException accessExc => new HttpErrorModel
         {
             Details = new HttpErrorModel.ErrorDetails
             {
                 Text = accessExc.Message
             },
             StatusCode = 403
         },
         _ => new HttpErrorModel
         {
             Details = new HttpErrorModel.ErrorDetails
             {
                 Text = "Неопределенная ошибка сервера!"
             },
             StatusCode = 500
         },
     });