How to catch HystrixTimeout Exception in Zuul - java

when web service does not respond in a time(timeout) and throwing HystrixTimeout Exception, i want to catch HystrixTimeout Exception in ZuulFilter. how can i handle that?
Note: in ZuulFilter, i catch my custom exception. Like a below code
#Override
public Object run() {
final RequestContext context = RequestContext.getCurrentContext();
final Object throwable = context.get(THROWABLE_KEY);
if (throwable instanceof ZuulException) {
ZuulException zuulException = (ZuulException) throwable;
}
return null;
}

this problem was not my real problem. firstly, i understood this. Because my app throwing SocketTimeoutException as a base exceptio. So if i can catch SocketTimeoutException, i can handle this problem but for this solution i need to get exceptions' cause of cause. I wrote a method like a below code.
private Throwable findRightException(Throwable th) {
Throwable throwable = th;
if (throwable.getCause() == null || throwable.getCause() instanceof SocketTimeoutException) {
return throwable.getCause();
}
return findRightException(throwable.getCause());

Related

AWS - SQS deletionPolicy on specific custom exception

In AWS sqs i need to consider message as failed and retry it only on specific custom exception rather than on all runtime exception
#SqsListener(value = "/MyQueueURL", deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS )
public void getMessageFromSqs(MyMessage message) {
log.info("message: {}", message);
// Ignore other exceptions
if(somecondition) {
throw new MyCustomException("Retry it"); //<--- Fail only on this exception
}
log.info("Success");
}
Then you need to use java try catch block, to hide the other errors. Although this concept does seem risky as ANY coding error you could lose data.
Since the deletion policy is on success it will automatically remove message from SQS.
#SqsListener(value = "/MyQueueURL", deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS )
public void getMessageFromSqs(MyMessage message) {
try {
log.info("message: {}", message);
// Ignore other exceptions
if(somecondition) {
throw new MyCustomException("Retry it"); //<--- Fail only on this exception
}
log.info("Success");
} catch(Exception e) {
log.info("error")
if (e instanceOf MyCustomException) {
throw e
}
}
}

handle checked exception in RxJava 2

I have some issue when I try to catch exception.
I have some method like this (legacy method) :
public String myLegacyMethod throws MyException() {
//do something or throw MyException in case of error
}
and I need to send a Single of this part and my solution is:
public Single<String> reactiveMethod() {
try {
String s = myLegacyMethod();
return Single.just(s);
} catch (Exception e) {
//log exception
return Single.error(e);
}
}
are there a way to handle an exception in reactive way? or maybe transform reactiveMethod in non-blocking code?
thanks for your answers.
You can use fromCallable in 2.x if MyException extends Exception:
public Single<String> reactiveMethod() {
return Single.fromCallable(() -> myLegacyMethod());
}

Catching Exception with JUnit #Test(expected=Exception.Class)

I am writing a test case using JUnit and I am trying to catch an Exception using #Test(expected=Exception.Class). For some reason I am unable to catch the exception. If I pass null it would throw NullPointerException and the test catches it because Exception is the parent class but on my Coverage report the exception is still not covered.
Method under test:
private static final String CONTENT_LENGTH = "Content-Length";
protected long getContentLength( MultivaluedMap<String, String> headers ) {
String length = headers.getFirst( CONTENT_LENGTH );
if( length != null ) {
try {
return Long.valueOf( length );
} catch( Exception e ) {}
}
return 0;
}
JUnit test case:
#Test(expected=Exception.class)
public void testGetContentLength() {
new TestBaseMessageBodyReader().getContentLength(null);
}
Any help would be appreciated.
Thanks
Catching generic exception is bad practice and even worse to catch an exception and do nothing. in your try catch you should catch NumberFormatException which is what Long.valueOf has the potential of throwing. Even then your jUnit will not never catch the exception because you are catching the exception but not doing anything with it, the method would always return 0 as it's currently written (provided you're not passing null)
Here is some code that would catch the exception on your unit test. I'd create two unit tests, one to catch your the first exception and one to catch the second.
protected long getContentLength(MultivaluedMap<String, String> headers)
{
if(null == headers)
{
throw new SomeCustomException("some message");
}
Long returnValue = 0;
String length = headers.getFirst(CONTENT_LENGTH);
try
{
returnValue = Long.valueOf(length);
}
catch (NumberFormatException e) {
// if you can recover handle it here
// if you can't recover then break the app
throw new SomeOtherCustomException("some other message");
}
return returnValue;
}

Catching and rethrowing an exception from a boolean method does return false whereas not doing anything causes the method not to return

I have a general query regarding the java programming language and how it deals with exceptions and methods returning boolean.
Please not that although the example below deals with Spring/Ldap/ActiveDirectory, my question is only about java and exceptions.
public boolean doAuthenticate(String userAndDomain, String password) {
UsernamePasswordAuthenticationToken userToken = new UsernamePasswordAuthenticationToken(replaceBackSlashWithAtSign(userAndDomain), password);
try {
Authentication authentication = adAuthenticationProvider.authenticate(userToken);
return authentication.isAuthenticated();
} catch (BadCredentialsException e) {
log.error("Authentication failed - wrong username\\password", e);
throw new BadCredentialsException("Authentication failed - wrong username\\password", e);
} catch (AuthenticationException e) {
log.error("Authentication failed - AuthenticationException", e);
throw new AuthenticationException("Authentication failed - AuthenticationException", e) { };
}
}
If any of BadCredentialsException or AuthenticationException is rethrown by the authenticate method, then the doAuthenticate method returns false.
However if for some reason another runtime exception is thrown by adAuthenticationProvider.authenticate(), then the method does not return false and does not return at all...
I am just curious to know why that is...
edit:
LdapAuthentifier authentifier = new LdapAuthentifierImpl();
boolean didAuthenticate = authentifier.doAuthenticate(VALID_USER, INVALID_PASSWORD);
A System.out.println of didAuthenticate does show false if one of the two specified exceptions are thrown whereas another exception halts execution of the program and the System.out.println is never reached...
edit 2:
public static void main(String[] args) {
LdapAuthentifier authentifier = new LdapAuthentifierImpl();
boolean didAuthenticate = authentifier.doAuthenticate(VALID_USER, INVALID_PASSWORD);
}
I understand what happened. Here is the explanation.
The exception I actually saw in the logs was BadCredentialsException but this exception is never thrown by adAuthenticationProvider.authenticate and therefore never rethrown by the below method.
What actually happened was that the authentication.isAuthenticated() was just returning false and I was passing this boolean value to the client code.
I am including the method again for clarity's sake:
#Override
public boolean doAuthenticate(String userAndDomain, String password) {
UsernamePasswordAuthenticationToken userToken = new UsernamePasswordAuthenticationToken(replaceBackSlashWithAtSign(userAndDomain), password);
try {
Authentication authentication = adAuthenticationProvider.authenticate(userToken);
return authentication.isAuthenticated();
} catch (BadCredentialsException e) {
log.error("Authentication failed - wrong username\\password", e);
throw new BadCredentialsException("Authentication failed - wrong username\\password", e);
} catch (AuthenticationException e) {
log.error("Authentication failed - AuthenticationException", e);
throw new AuthenticationException("Authentication failed - AuthenticationException", e) { };
}
}

EasyMock to test SecurityException

I am trying to use easyMock to write a test, that tests SecurityException in the following code.
eg. for NumberFormatException I use the below.
EasyMock.expect(mockEntityManager.find(UserProfile.class,"abc")).andThrow(new
NumberFormatException());
Any ideas on what to expect to throw SecurityException?
public Object getAsObject(FacesContext facesContext, UIComponent
uiComponent, String s) {
EntityManager entityManager = (EntityManager)Component.getInstance("entityManager");
if (s == null || s.equals("null")) {
return null; } else {
try {
long i = Long.parseLong(s);
return entityManager.find(UserProfile.class, i);
} catch (NumberFormatException e) {
logger.error(e);
} catch (SecurityException e) {
logger.error(e);
} }
return null; }
I have the feeling that you haven't written that code, and that's why you're wondering what might throw SecurityException. The answer is nothing, as long as you're using a good implementation of EntityManager.
The documented version of EntityManager.find()enter link description here doesn't throw SecurityException. BUT if you're running that code inside a J2EE app server that uses a custom version of EntityManager, it could be that it throws that exception... But I don't think it should.
Thanks for your responses..here is what I did to expect SecurityException.
MyClass abc = new MyClass();
EasyMock.expect(mockEntityManager.find(MyClass.class,111L)).andThrow(new SecurityException());
EasyMock.replay(mockEntityManager);
Object target = abc.getAsObject(mockFacesContext, mockUiComponent,"111");
Assert.assertEquals(null, target);

Categories