I have below code to check this error but I am not getting timeout error its going to else condition
Response response = null;
try {
response = client.getResponse(URI.create(uri), headers, reuest);
} catch (Exception ex) {
if(ex instanceof SocketTimeoutException){
throw new ExternalClientException(Errors.TIMEOUT_ERROR);
} else {
throw new ExternalClientException(Errors.UNEXPECTED_ERROR);
}
}
You need to catch feign.RetryableException instead of SocketTimeoutException.
javadoc
Please send all code of class. You need to provide class of "client" variable so people can help.
One more thing, instead of checking instance of exception in "catch" clause, you should use multiple catching like this:
Response response = null;
try {
response = client.getResponse(URI.create(uri), headers, reuest);
} catch (SocketTimeoutException ex1) {
throw new ExternalClientException(Errors.TIMEOUT_ERROR, ex1);
} catch (Exception ex2) {
throw new ExternalClientException(Errors.UNEXPECTED_ERROR, ex2);
}
Related
This is my method.
public boolean authenticateAndPollCallbackResult(BankIdAuthRequest bankIdAuthRequest) {
ResponseEntity<BankIdAuthResponse> authResponse = bankIdAuthentication(bankIdAuthRequest);
AbstractApplicationForm applicationForm = applicationFormRepository.findByToken(bankIdAuthRequest.getRefID());
try {
//Add new bankId authentication to database.
BankIdAuthenticationEntity bankIdAuthenticationEntity = new BankIdAuthenticationEntity();
bankIdAuthenticationEntity.setAbstractApplicationForm(applicationForm);
bankIdAuthenticationEntity.setAuthStatus(STATUS_PROGRESS);
bankIdAuthenticationEntity.setOrderReference(authResponse.getBody().getOrderRef());
bankIdAuthenticationEntity.setAutoStartToken(authResponse.getBody().getAutoStartToken());
Long bankIdAuthenticationId = bankIdAuthenticationRepository.save(bankIdAuthenticationEntity).getId();
BankIdAuthenticationEntity.AuthStatus authStatus;
do {
TimeUnit.MILLISECONDS.sleep(1500);
authStatus = getAuthStatus(bankIdAuthenticationId);
if (authStatus == BankIdAuthenticationEntity.AuthStatus.COMPLETED)
return true;
if (authStatus == BankIdAuthenticationEntity.AuthStatus.FAILED || authStatus == BankIdAuthenticationEntity.AuthStatus.NOT_ASSIGNED)
return false;
} while (authStatus == BankIdAuthenticationEntity.AuthStatus.PROGRESS);
} catch (InterruptedException e) {
log.error("InterruptedException: ", e);
Thread.currentThread().interrupt();
} catch (NullPointerException e) {
log.error("Either BankId API not responding correctly. Check server connection", e);
} catch (Exception e) {
log.error("Exception: Polling collect endpoint method failed", e);
}
return false;
}
Now SonarQube warns that these two lines can return null (and they can):
bankIdAuthenticationEntity.setOrderReference(authResponse.getBody().getOrderRef());
bankIdAuthenticationEntity.setAutoStartToken(authResponse.getBody().getAutoStartToken();
But i don't know what the best way to check for null is.
I tried using Objects.requireNonNull which throws a null and the i figured the null check would catch it but it just feel ugly and not correct.
Any suggestions or absolute correct ways of doing this that i might have missed?
The problem is that authResponse.getBody() can be null. Right?
In this cas you should check it before an either throw an exception or not execute the two lines:
if(authResponse.getBody() != null {
bankIdAuthenticationEntity.setOrderReference(authResponse.getBody().getOrderRef());
bankIdAuthenticationEntity.setAutoStartToken(authResponse.getBody().getAutoStartToken();
})
or
if(authResponse.getBody() == null {
throw new ....Exception();
}
And if the problem is that getOrderRef() or getAutoStartToken() could return null, you should check these values before and handle the cases when they are null.
Oops guys! Beauty? I'm trying to get a byte list[] in my Rest template's response, but my exchange isn't accepting the new ParameterizedTypeReference<List<byte[]>>() {} , could someone help me?
ResponseEntity<List<byte[]>> response = null;
try {
response = restTemplate.exchange(parametros.get("SERVICE_HUB2_BASE_URL") + "/fw/v1/pdf/kms/assinaturas",
HttpMethod.POST, entity, new ParameterizedTypeReference<List<byte[]>>() {});
} catch (HttpServerErrorException e) {
e.printStackTrace();
throw new ClientException(e.getStatusCode().value(), e.getStatusText());
} catch (HttpClientErrorException e) {
e.printStackTrace();
throw new ClientException(e.getStatusCode().value(), e.getStatusText());
} catch (Exception e) {
e.printStackTrace();
}
Hi As per the mouse hower it's pointing to different method.
Please check import statement for rest template.
both ways should be fine .
ResponseEntity<Collection<byte[]>> responseEntityOne = restTemplate.exchange(formattedUrl, HttpMethod.POST, entity,
new ParameterizedTypeReference<Collection<byte[]>>(){});
ResponseEntity<List<byte[]>> responseEntityOne1 = restTemplate.exchange(formattedUrl, HttpMethod.POST, entity,
new ParameterizedTypeReference<List<byte[]>>(){});
I'd like to allow all handler methods in a Razor Page to be wrapped by some sort of logic to handle specific exceptions that are more or less validation exceptions.
I've tried the following, but still get the developer exception page:
public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
try
{
await next();
}
catch(NotImplementedException ex)
{
_logger.LogWarning(ex, ex.Message);
ModelState.AddModelError(string.Empty, "Oops... this isn't all done yet.");
context.Result = Page();
}
catch (DomainValidationException ex)
{
ModelState.Include(ex.Results);
context.Result = Page();
}
}
The exception does not appear to bubble up from the await next() call and is handled in aspnetcore somehow.
It turns out that the next returns a result that needs to be inspected to get the exception and return the result.
The final implementation looks something like this:
public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
var result = await next();
if (result.Exception != null)
{
if (result.Exception is NotImplementedException nex)
{
result.ExceptionHandled = true;
_logger.LogWarning(nex, nex.Message);
ModelState.AddModelError(string.Empty, "Oops... this isn't all done yet.");
}
else if (result.Exception is DomainValidationException dex)
{
result.ExceptionHandled = true;
ModelState.Include(dex.Results);
}
if (result.ExceptionHandled)
{
result.Result = Page();
}
}
}
I am trying to write a simple JAVA REST Client through which I want to PUT/GET elasticsearch document information.
PUT is working fine, my json data got added into index.
But the problem is GET, Response Code is 200, but it is not returning any data.
Can anyone please help.
public static String httpGet(String resturl){
String output = null;
try {
URL url = new URL(resturl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
//System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
I am calling as
RestClient.httpGet("http://localhost:9200/gabsindex/employee/_search")
You println call is currently commented out. If you uncomment it, you'll get the response from the server on one single line, something like
{"took":50,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":7056,"max_score":1.0,"hits":[...]}}
If you are trying to follow this approach educationally, this can be ok. Remember, nonetheless, that there are a number of libraries that can be used exactly for this use. You should check out the clients page.
In the following, ar.GetResponseAsString() just throws an exception.
Here is my code:
AsyncCallback GetTheResponse = ar =>
{
try
{
var result = ar.GetResponseAsString();
Debug.WriteLine(string.Format("ResponseStream:::{0}", result));
callback(result, null);
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
What am I doing wrong?
Catch the WebException that the 400 is throwing then grab the response from the exception message. That's where your error response is hiding