AWS DynamoDB TransactionWriteItem Retry Example - amazon-dynamodb

i'm trying to look for an example on how to retry whenever we get a exception out of dynamoDBMapper.transactionWrite. Thanks in Advance.
TransactionWriteRequest transactionWriteRequest = new TransactionWriteRequest();
transactionWriteRequest.withIdempotencyToken(generateNewToken());
transactionWriteRequest.addUpdate(idMapping);
executeTransactionWrite(transactionWriteRequest);
return idMapping;
}
public void executeTransactionWrite(TransactionWriteRequest transactionWriteRequest) {
try {
dynamoDBMapper.transactionWrite(transactionWriteRequest);
} catch (DynamoDBMappingException ddbme) {
System.err.println("Client side error in Mapper, fix before retrying. Error: " + ddbme.getMessage());
} catch (ResourceNotFoundException rnfe) {
System.err.println("One of the tables was not found, verify table exists before retrying. Error: " + rnfe.getMessage());
} catch (InternalServerErrorException ise) {
System.err.println("Internal Server Error, generally safe to retry with back-off. Error: " + ise.getMessage());
} catch (TransactionCanceledException tce) {
System.err.println("Transaction Canceled, implies a client issue, fix before retrying. Error: " + tce.getMessage());
} catch (Exception ex) {
System.err.println("An exception occurred, investigate and configure retry strategy. Error: " + ex.getMessage());
}
}

Related

SQL Error executing INSERT: [SQLITE_BUSY] The database file is locked

I am using sqlite as db in my Micronaut application getting the sqlite busy error in the below code:
#SneakyThrows
#TransactionalAdvice(value = EmpDao.DATASOURCE, propagation = TransactionDefinition.Propagation.REQUIRES_NEW)
public void storeEmp(EmpDto empDto) {
String id = empDto.getId();
try {
if (empDao.existsById(id)) {
log.debug("updating emp for id {}", empDto.getId());
empDao.update(EmpEntity.builder()
.id(id)
.data(getJson(empDto))
.entryCreatedAt(timeService.nowDateTime().toEpochSecond(ZoneOffset.UTC))
.build());
} else {
empDao.save(
EmpEntity.builder()
.id(id)
.data(getJson(empDto))
.entryCreatedAt(timeService.nowDateTime().toEpochSecond(ZoneOffset.UTC))
.build());
}
}catch(Exception e){
log.error("emp db save/update failed for id {} ",id, e);
}
}
#SneakyThrows
#TransactionalAdvice(value = EmpDao.DATASOURCE, propagation = TransactionDefinition.Propagation.REQUIRES_NEW)
public void storeEmployees(List<Emp> empDtos) {
try {
empDao.saveAll(empDto);
} catch (Exception ex) {
log.warn("saveAll failed", ex);
empDtos.forEach(this::storeEmp);
}
}
In stacktrace I can see first saveAll getting failed becuase of Primary keyconstraint Issue, that might be because of duplicate emp ids in the list
SQL error executing INSERT: [SQLITE_CONSTRAINT_PRIMARYKEY] A PRIMARY KEY constraint failed
and After that when It tried to save/update each emp object independently through storeEmp method in forEach, it's failing with the sqlite busy exception.
What I am not sure if saveAll is already failed, how there can be multiple connection to sqlite. Can anyone suggest what's wrong with the above code.
Thanks

Google Firebase how to catch specific Auth exception errors - Unity

-How to catch Auth exception errors - Unity
-How to catch if user/email exists - Unity
-Where to find the list of Auth exceptions error code - Unity
*I found a lot of answers for Android so I decided to finally write my solution for Unity.
The answer is simple- either use the following function on the task you are trying to achieve -
protected bool LogTaskCompletion(Task task, string operation)
{
bool complete = false;
if (task.IsCanceled)
{
Debug.Log(operation + " canceled.");
}
else if (task.IsFaulted)
{
Debug.Log(operation + " encounted an error.");
foreach (Exception exception in task.Exception.Flatten().InnerExceptions)
{
string authErrorCode = "";
Firebase.FirebaseException firebaseEx = exception as Firebase.FirebaseException;
if (firebaseEx != null)
{
authErrorCode = String.Format("AuthError.{0}: ",
((Firebase.Auth.AuthError)firebaseEx.ErrorCode).ToString());
}
Debug.Log("number- "+ authErrorCode +"the exception is- "+ exception.ToString());
string code = ((Firebase.Auth.AuthError)firebaseEx.ErrorCode).ToString();
Debug.Log(code);
}
}
else if (task.IsCompleted)
{
Debug.Log(operation + " completed");
complete = true;
}
return complete;
}
The printed output Debug.Log(code) is the exception code you are looking for. Now you can compare it - if (code.Equals("some specific exception....")) and complete it with your code.
Example:
How to catch if user/email exists
Let's say we sign up a new user with CreateUserWithEmailAndPasswordAsync and we want to catch the error " The email address is already in use"
We can use my function to find out what the error code we need to compare and it will print to output "EmailAlreadyInUse". Next all I need to do is to check if ((code).Equals("EmailAlreadyInUse"))
-Another possible way is to find the error code in a list-
List of Auth exceptions error code FOR UNITY
All the exceptions are under class Firebase.Auth.AuthError you can see them either on your code editor, or on Firebase website under - Unity - Firebase.Auth - Overview (under AuthError).
Hope it helps!

Error for GetStringAsync if triggered by ScheduledAgent but no error during WP8 App usage

I have a wrapper for the webclient that I am using to retrieve some data. This same function is being used by the WP8 App and also used by the WP8 ScheduledAgent.
Somehow, when the function is used by the WP8 App, there is no error and it returns correctly.
However, when the ScheduledAgent uses the function, it erred out at the bold code below. I tried a try catch but it is not catching. Via Debugger, the GetSTringAsync(uri) had completed without any exception. The error seemed to be only happening when it is assigning the return Task to the result string.
The error I received is:
An unhandled exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll
public class HttpClient : WebClient
..
private async Task GetStringAsync(string strUri)
{
Uri uri = new Uri(strUri);
string result = string.Empty;
try
{
result = await GetStringAsync(uri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return result;
}
...
private Task GetStringAsync(Uri requestUri)
{
TaskCompletionSource tcs = new TaskCompletionSource();
try
{
this.DownloadStringCompleted += (s, e) =>
{
if (e.Error == null)
{
tcs.TrySetResult(e.Result);
}
else
{
tcs.TrySetException(e.Error);
}
};
this.DownloadStringAsync(requestUri);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
if (tcs.Task.Exception != null)
{
throw tcs.Task.Exception;
}
return tcs.Task;
}
Please advise if I am missing something.
My problem is because I am using pushpin as one of my object types within my Model. Apparently, in the scheduled agent, it is not able to access that object type and thus threw the above error.

Handle WebFaultException to display error message on label

In my WCF REST service, there is a method GetUser(username), which will
throw new WebFaultException<string>("there is no this user", HttpStatusCode.NotFound);
In my asp.net client, I want to catch above exception and show "there is no this user" on a label. But when I try coding as follow:
MyServiceClient client = new MyServiceClient;
try
{
client.GetUser(username);
}
catch (Exception ex)
{
Label.Text = ex.Message;
}
It turns out show the message "NotFound" instead of "there is no this user".
How can i do to show the message "there is no this user"?
20/4
In my REST service:
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json,
UriTemplate = "{username}")]
void GetUser(username);
.svc class :
public void GetUser(username)
{
try
{
Membership.GetUser(username);
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
}
catch (Exception ex)
{
throw new WebFaultException<string>("there is no this user", HttpStatusCode.NotFound);
}
}
If you look into the documentation, it's obvious that you should be showing the Detail, not the Message. Your line should be:
MyServiceClient client = new MyServiceClient;
try
{
client.GetUser(username);
}
catch (FaultException<string> ex)
{
var webFaultException = ex as WebFaultException<string>;
if (webFaultException == null)
{
// this shouldn't happen, so bubble-up the error (or wrap it in another exception so you know that it's explicitly failed here.
rethrow;
}
else
{
Label.Text = webFaultException.Detail;
}
}
EDIT: changed exception type
Also, you should be catching the specific exception (WebFaultException<string>) that you're interested in, not any-old exception that happens to be thrown. Especially, as you'll only have the Detail on the WebFaultException<string> type, it's not on Exception.
See the WebFaultException Class

How to capture http request/response traffic results

I want to Capture Http Request/Response Traffic results(URL,Method,Type etc) with c# Windows Form App as manually.
An Example :
Run ie explorer-> Tools -> F12 Developer Tools->Network Tab-Star Capture
How can I solve this problem. (Any use of the sdk. winpcap etc)
How to trace a road?
Try the below:
...
HttpWebRequest request =(HttpWebRequest)WebRequest.Create(HttpUtility.UrlDecode(<url>));
...
try
{
HttpWebResponse response =(HttpWebResponse)request.GetResponse();
WebHeaderCollection headers = response.Headers;
...
}
catch(WebException exc) { "HTTP EXCEPTION: " + exc.Message +" " + exc.Status; }
catch(ProtocolViolationException exc) { exc.Message; }
catch(UriFormatException exc) { exc.Message; }
catch(NotSupportedException exc) { exc.Message; }
catch(IOException exc) { exc.Message; }

Resources