Rakesh Kumar
Rakesh Kumar

Reputation: 3129

Cosmos DB: Response status code does not indicate success: BadRequest (400); Substatus: 1001; Reason: ();

I am using Cosmos DB repository and trying to add new item for below object.

[Container(nameof(Notifications))]
    [PartitionKeyPath("/UserUUId")]
    public class Notifications : Item
    {
        [JsonProperty(PropertyName = "RequestID", Order = 2)]
        public string RequestID { get; set; }

        [JsonProperty(PropertyName = "NotificationType", Order = 3)]
        public int NotificationType { get; set; }

        [JsonProperty(PropertyName = "SubType", Order = 4)]
        public string SubType { get; set; }

        [JsonProperty(PropertyName = "UserUUId", Order = 5)]
        public string UserUUId { get; set; }

        [JsonProperty(PropertyName = "Payer", Order = 6)]
        public string Payer { get; set; }

        [JsonProperty(PropertyName = "PayerName", Order = 7)]
        public string PayerName { get; set; }

        [JsonProperty(PropertyName = "Account", Order = 8)]
        public string Account { get; set; }

        [JsonProperty(PropertyName = "AccountName", Order = 9)]
        public string AccountName { get; set; }

        [JsonProperty(PropertyName = "Created", Order = 10)]
        public DateTime Created { get; set; }

        [JsonProperty(PropertyName = "Updated", Order = 11)]
        public DateTime? Updated { get; set; }

        [JsonProperty(PropertyName = "Status", Order = 12)]
        public int Status { get; set; }

        [JsonProperty(PropertyName = "MetaData", Order = 13)]
        public Dictionary<string, string> MetaData { get; set; }

        protected override string GetPartitionKeyValue() => UserUUId;
    }

This is my code code to add new item:

public class UINotificationPublisher : IUINotificationPublisher
{

   private readonly IRepository<Notifications> _uiNotificationsRepository;

    public UINotificationPublisher(
        IRepositoryFactory factory
    
        )
    {
        _uiNotificationsRepository = factory.RepositoryOf<Notifications>();

    }

    public async Task PublishAsync(IEnumerable<UserSubscriptions> userSubscriptions, CardGroupEvent @event, ILogger logger)
    {
        try
        {
            var uiSubscriptions = userSubscriptions
                .Where(x => x.Events.Any(y => y.EventType == (int)EventType.CARD_GROUP_CHANGED && y.Channels.Contains((int)ChannelType.UI)));

            if (uiSubscriptions.Any())
            {
                logger.LogInformation($"UI notification subscriptions found, requestID:{@event.RequestID}");

                List<Notifications> uiNotifications = new List<Notifications>();

                foreach (var item in uiSubscriptions)
                {
                    logger.LogInformation($"creating UI notification for UUID:{item.UUID}. requestID:{@event.RequestID}");

                    uiNotifications.Add(CreateItemAsync(item, @event));

                    logger.LogInformation($"successfully created UI Notification for UUID:{item.UUID}: {@event.RequestID}");
                }
                await _uiNotificationsRepository.CreateAsync(uiNotifications);
            }
            else
                logger.LogInformation($"No UI notification subscriptions found: requestID:{@event.RequestID}");
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private Notifications CreateItemAsync(UserSubscriptions userSubscription, CardGroupEvent @event)
    {
        Notifications notifications = new Notifications
        {
            Id = Guid.NewGuid().ToString(),
            Created = DateTime.UtcNow,
            RequestID = @event.RequestID,
            NotificationType = (int)EventType.CARD_GROUP_CHANGED,
            SubType = @event.EventSubType,
            UserUUId = userSubscription.UUID,
            Payer = @event.PayerNumber,
            PayerName = @event.PayerName,
            Account = @event.AccountNumber,
            AccountName = @event.AccountName,
            MetaData = GetMetaData(@event),
            Status = (int)NotificationStatus.UnRead

        };
      
        return notifications;
        
    }

    private Dictionary<string, string> GetMetaData(CardGroupEvent @event)
    {
       

        var metaData = new Dictionary<string, string>();
     
        metaData.Add(nameof(@event.AccountNumber), @event.AccountNumber);
        metaData.Add(nameof(@event.AccountName), @event.AccountName);
      
        return metaData;
    }
}

Cosmos DB Respository CreateAsync:

enter image description here

I am getting below exception while inserting new item:

"Response status code does not indicate success: BadRequest (400); Substatus: 1001; ActivityId: 68af0c72-ff2d-4055-8898-b94a08f18ead; Reason: ();"

Below is the stack trace:

at Microsoft.Azure.Cosmos.ResponseMessage.EnsureSuccessStatusCode() at Microsoft.Azure.Cosmos.CosmosResponseFactoryCore.ProcessMessage[T](ResponseMessage responseMessage, Func2 createResponse) at Microsoft.Azure.Cosmos.CosmosResponseFactoryCore.CreateItemResponse[T](ResponseMessage responseMessage) at Microsoft.Azure.Cosmos.ContainerCore.d__541.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Microsoft.Azure.Cosmos.ClientContextCore.d__391.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at Microsoft.Azure.Cosmos.ClientContextCore.d__301.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Microsoft.Azure.CosmosRepository.DefaultRepository1.d__7.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Threading.Tasks.ValueTask1.get_Result() at System.Runtime.CompilerServices.ValueTaskAwaiter1.GetResult() at CardGroupEventSubscriber.Publishers.UINotificationPublisher.d__2.MoveNext() in C:\notification-subscribers\dev\Notification-Microservices\CardGroupEventSubscriber\CardGroupEventSubscriber\Publishers\UINotificationPublisher.cs:line 49

Upvotes: 1

Views: 8374

Answers (1)

Matias Quaranta
Matias Quaranta

Reputation: 15583

This is covered in the Troubleshooting doc for Bad Request

A response with this error means you are executing an operation and passing a partition key value that does not match the document's body value for the expected property. If the collection's partition key path is /myPartitionKey, the document has a property called myPartitionKey with a value that does not match what was provided as partition key value when calling the SDK method.

You are not sharing the code that calls the Cosmos DB SDK (just calls to some repository object) so it's hard to point to the right code, but if you are calling for example:

container.CreateItem(<item>, new PartititionKey(pkValue))

This error would mean the new PartitionKey(pkValue) you are passing is incorrect, it is not the value of the container's Partition Key Definition property in the item.

The code might be assuming the Partition Key Definition is on (for example /Payer) but the Container's actual Partition Key Definition is another (for example \id).

Upvotes: 2

Related Questions