Dynamodb nodejs client throws an exception and the exception is an empty object - amazon-dynamodb

I get this exception several times in the logs. I am using nodejs and the dynamodb client throws an exception when inserting an object. I have wrapped the code in try catch block and log the exception. But the exception is just an empty object. Any insights would be awesome.
try {
// documentClient is the instantiated dynamo client
await documentClient.put(params).promise();
} catch (e) {
console.log(e);
}

Related

How to check if a call to Cosmos DB succeeded or failed

What would be the best way to check if a call to Cosmos DB succeeded or failed? Should I check the status code in the response or catch an exception or both? Are there any cases where the response status code is not success, but no exception is thrown?
ContainerResponse containerResponse = null;
try
{
containerResponse = await cosmosClient.GetContainer(databaseId, containerId).ReadContainerAsync();
if (containerResponse.StatusCode != HttpStatusCode.Ok)
{
// the call failed. do something here.
}
}
catch (CosmosException ex) when (ex.StatusCode != HttpStatusCode.NotFound)
{
throw;
}
...
In V3 SDK, if you are using the Stream APIs (ReadContainerStreamAsync), then no exceptions will be thrown for failures and you should inspect the status code of the response.
If you use the Typed APIs (ReadContainerAsync), then any failure would throw a CosmosException.
Reference: https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Exceptions.md#typed-apis

What is causing my DbUpdateConcurrencyException?

In my .NET Core Web API, I have implemented the transactional outbox pattern to monitor a database table and publish messages to an Azure Service Bus topic whenever a record appears in the database table. This takes place within a hosted service class that inherits from Microsoft.Extensions.Hosting.BackgroundService. This is a stripped-down version of what I have:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
IEnumerable<RelayMessage> messagesToSend = new List<RelayMessage>();
// _scopeFactory is an implementation of Microsoft.Extensions.DependencyInjection.IServiceScopeFactory:
using (var scope = _scopeFactory.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>();
while (!stoppingToken.IsCancellationRequested)
{
messagesToSend = await dbContext.RelayMessage.ToListAsync();
foreach (var message in messagesToSend)
{
try
{
await SendMessageToAzureServiceBus(message);
dbContext.RelayMessage.Remove(message);
dbContext.SaveChanges();
}
catch (Exception ex)
{
Log.Error(ex, $"Could not send message with id {message.RelayMessageId}.");
}
}
await Task.Delay(5000, stoppingToken);
}
}
await Task.CompletedTask;
}
catch (Exception ex)
{
Log.Error(ex, "Exception thrown while processing messages.");
}
The records are being deleted from the database, but the following exception gets thrown on the call to SaveChanges():
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ThrowAggregateUpdateConcurrencyException(Int32 commandIndex, Int32 expectedRowsAffected, Int32 rowsAffected)
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeResultSetWithoutPropagation(Int32 commandIndex, RelationalDataReader reader)
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.Consume(RelationalDataReader reader)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IList`1 entries)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IList`1 entriesToSave)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(DbContext _, Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at ReinsuranceReferenceSystemApi.Services.ServiceBus.ParticipantPublishingService.ExecuteAsync(CancellationToken stoppingToken)
I did check out the link in the exception message, but am not sure if the information applies to my situation. The RelayMessage instance is created and saved to the database (in a method not shown here), then this method reads it and deletes it. There aren't any modifications of this type anywhere in the application, so I'm unclear on how this could be a concurrency issue.
I'd appreciate any help.
EDIT:
Here's the registration of my DbContext in Startup.cs:
services.AddDbContext<MyDbContext>(o =>
{
o.UseSqlServer(Configuration.GetConnectionString("MyConnectionString"));
});

How to handle socket exception when net is not there?

I want to display an error screen if net is not there. I am not using connectivity package because I don't want continuous check. I just want to handle exception while calling backend api and display the screen. I am unable to catch the exception.
I found this issue and this question about socket exceptions but none seem to help me.
This is how I call my backend api -
callBackendApi() async {
try {
http.Response response = await Future.value(/*api call here*/)
.timeout(Duration(seconds: 90), onTimeout: () {
print('TIME OUT HAPPENED');
});
} catch (exception) {
Fluttertoast.showToast(msg: 'Check internet connection.');
print('Error occurred' + exception.toString());
}
}
I use dio like this:
try {
var formData = FormData.from(Map<String, dynamic>.from(data));
var response = await dio.post(
uri,
data: formData,
);
jsonResponse = json.decode(response.data);
} on DioError catch (e) {
if (DioErrorType.RECEIVE_TIMEOUT == e.type ||
DioErrorType.CONNECT_TIMEOUT == e.type) {
throw CommunicationTimeoutException(
"Server is not reachable. Please verify your internet connection and try again");
} else if (DioErrorType.RESPONSE == e.type) {
// 4xx 5xx response
// throw exception...
} else if (DioErrorType.DEFAULT == e.type) {
if (e.message.contains('SocketException')) {
throw CommunicationTimeoutException('blabla');
}
} else {
throw CommunicationException("Problem connecting to the server. Please try again.");
}
}
My solution is to import 'dart.io' in order to catch SocketException from try block:
import 'package:http/http.dart' as http;
import 'dart:io';
try{
//Handle you network call code block in here
}on SocketException catch(_){
//To handle Socket Exception in case network connection is not available during initiating your network call
}
Well i don't know if my answer will be solving your question but days ago i had a problem little bit likely yours but in my case was using firebase realtime database. I was asking to myself how can i protect my app from network fails like no internet connection available? Well i am not using connectivity package too so i solve this problem with an approach that you already has been try using a timeout for network operations. I will share two snipets with differents approaches that i had implemented to handle this kind of problem adding some comments trying explain the differences between them.
Approach 1 - Setting timeout outside from network request method
Well the snipet below is a simple firebase database request where _viewsRef is a DatabaseReference and the once method do the request and returns me a Future with or without data.
// get users visualization from realtime database and returns a future
static Future<DataSnapshot> getUserVisualizations({#required String uid}) async {
return _viewsRef.child(uid).limitToLast(50).once();
}
In my BLoC component class i am calling the method below and setting a timeout to the future that is returned.
myBlocComponentMethod(){
//.. some work and finally the call
FirebaseUserViewsHelper.getUserVisualizations(uid: _currentUid)
.then(
(dataSnapshot){
if (dataSnapshot.value == null) {
// do some things to handle no data
}
else {
/// handle your data here
});
}
} // setting timeout here is an important point
).timeout( Duration(seconds: Constants.NETWORK_TIMEOUT_SECONDS),
onTimeout: (){
// method to handle a timeout exception and tell to view layer that
// network operation fails
// if we do not implement onTimeout callback the framework will throw a TimeoutException
} );
}
Well what is the point here? In this case if the timeout expires and future is not completed yet onTimeout callback is called and there i can tell to the view layer that network operation fails and show to the user some widget about it. But even with timeout expired the request to firebase database stays happening again and again, it's like the async event of request the database stays on dart event queue. I think this behavior is bad for performance aspects but if you're building your UI using a StreamBuilder with a little logic and code your requested data will be available right when you internet connection is back and with BLoC pattern the UI can respond easily to this event and we don't need provide a refresh button by example to user make the request again. I don't know if this is the right approach to implement this behavior but it works.
Approach 2 - Setting timeout inside from network request method
Below another firebase database request method
static Future<DataSnapshot> readUserNode( {#required String uid} ) async
=> USERS_REFERENCE.child(uid).once()
.timeout( Duration(seconds: Constants.NETWORK_TIMEOUT_SECONDS ) );
//note: Without timeout callback this line will throw a TimeoutException if the time expires
The usage in another BLoc component:
myBlocComponentMethod2(){
for( String uid in iterable ){
FirebaseUserHelper.readUserNode(uid: uid)
.then( (userSnapshot){
if (userSnapshot.value == null){
// do your stuffs
}
else {
// more stuffs to do
}
}).catchError( (error){
// when timeout expired we will catch the TimeoutException HERE and handling telling
// the UI what we need
} );
}
}
The big difference here that i get was in the behavior. In this second case since i put the timeout inside the request method when the timeout expires the request event do not run anymore, it's like that request event is removed from dart event queue. This can be good from performance perspective but now we need provide a refresh button in UI for user do the data again to get data from internet again.
I don't know if this workaround will solve your problem because you tell about SocketException what is not the case that i has described and i don't know what api you are using to make your requests. Anyway i hope that the concepts described in this post helps you implement a solution in your problem.

Swift 2.0: throw exception within an asynchronous piece of code

I am trying to implement the log in service for an application, and I would like to throw an exception if the response status code is not equal to 200. I am using Alamofire as HTTP networking library.
static func loginWithUsername(username: String, andPassword password: String) throws {
let action = "SmartShoppers/login"
let url = baseUrl + action
Alamofire.request(.POST, url, parameters: ["username": username, "password": password])
.response { request, response, data, error in
if response?.statusCode != 200 {
throw ServiceError.LogInError
}
}
}
This is the ServiceError enum definition:
enum ServiceError: ErrorType {
case LogInError
}
What I want to do deal this exception when it is thrown in a function which is called when a button is pressed. This function is in the ViewController class associated with the ViewController that contains that button. The code that is going to be executed is:
do {
try Service.loginWithUsername(username, andPassword: password)
} catch {
// SHOW AN ALERT MESSAGE
}
Why am I receiving the message Cannot call value of non-function type 'NSHTTPURLResponse'? Is it the correct way to implement this service? If not please help me.
The closure that you are passing to the response method does not include throws in its signature, so you will not be able to throw an exception from within it.
IMO this is not a case where you would want to throw an exception, anyways - a non-200 response code is not an exceptional error / failure, and I wouldn't try to use an exception here as a means of control flow.

Log an exception without throwing it when using ELMAH

I am using ELMAH for logging in ASP.Net app.
My question is will the following line : Elmah.ErrorSignal.FromContext(System.Web.HttpContext.Current).Raise(ex), when used within a catch block throw the exception to the caller or simply log it and send out an error email?
try
{
...
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromContext(System.Web.HttpContext.Current).Raise(ex);
//do some special processing
}
Your code logs the thrown exception (ex) in ELMAH and returns successful to the caller. In other words, Raise does not throw an exception.
If your catch block re-throws ex or throw a new exception, both ex and the new exception are logged to ELMAH and a status code 500 is returned to the caller.

Resources