This is My code
from("direct:test-POST")
.doTry()
.process(new Processor() {
#Override
public void process(Exchange arg0) throws Exception {
throw new NullPointerException(" Null value");
}
})
.doCatch(NullPointerException.class)
.log("${exception}") // This Prints NullPointer Exception
.process(new Processor() {
#Override
public void process(Exchange arg0) throws Exception {
System.out.println( arg0.getException() ); //This prints Null
}
})
.end();
Am using jetty:run to run this camel route.
How do I catch the exception. It prints the exception correct in log. but inside the processor, the exception is null. what am I missing
I would think the exception is found on a property on the exchange. Something like:
Throwable caused = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, NullPointerException.class);
assertNotNull(caused);
Related
While writing unit test case for method someMethod1, I have a use case where I'm trying to ensure that an abstract exception (AnalysisException) is thrown when method (someMethod2) is called. Class under test is JdbcTemplateSampleImpl .
public class JdbcTemplateSampleImpl {
public void someMethod1() {
someMethod2();
}
private void someMethod2() throws AnalysisException {
// some code here
}
}
I am using PowerMockito to do like this
#Test(expected = com.test.AnalysisException.class)
public void abstractClassExceptionCheck2Test1() throws Throwable {
JdbcTemplateSampleImpl jdbcTemplateSampleImpl1 =
PowerMockito.spy(jdbcTemplateSampleImpl0);
PowerMockito.doThrow(mock(AnalysisException.class)).
when(jdbcTemplateSampleImpl1,"classCheck2");
jdbcTemplateSampleImpl1.abstractClassExceptionCheck2();
}
But while executing test case , i'm getting an error like this
java.lang.Exception: Unexpected exception, expected "com.test.AnalysisException" but was "java.lang.NullPointerException"
Mock the exception outside of the doThrow method call.
AnalysisException e = mock(AnalysisException.class);
PowerMockito.doThrow(e).
when(jdbcTemplateSampleImpl1,"classCheck2");
I try to test my Exception JUnit and the test doesn't pass I have this error trace :
org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnitAndHigherRunnerImpl.java:37)
and
org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
and here is my code :
PatientEntityFacade pef = new PatientEntityFacade();
Mockito.when(pef.findByNumber(5555)).thenReturn(patientEntity);
#Rule
public ExpectedException thrown = ExpectedException.none();
#Test
public void shouldThrow() throws PatientNotFoundException
{
thrown.expect(PatientNotFoundException.class);
thrown.expectMessage("personalized exception no patient found");
try {
pef.findByNumber(5555);
} catch (com.patient.facade.PatientNotFoundException e) {
e.printStackTrace();
}
}
If you watn to test your Exception, then do it the right way.
Define when Exception should be thrown.
in #BeforeClass if every Method should
in #Test-method if only this Method should throw it.
Notice, that you can use any(X.class) if other methods got other values for it.
DonĀ“t try-catch in unit-tests.
Catch it this way and if there is no Exception, the test will fail.
#Test(expected = PatientNotFoundException.class)
public void shouldThrow()
pef.findByNumber(5555);
}
in my Junit tests I have a test case that must be fail only when IOexception is throwing by my object under test.
So ,if my object under test throw IllegalStateException (or other Error or Exception) my test case is OK but if my object under test throw IOexception my test case must be fail.
How can I do it ?
Thanks for all.
You can use the expected exception rule
#Rule
public ExpectedException expected = new ExpectedException();
#Test
public void doSomethingWithNoIOException() {
// we expect an exception that's NOT an instance of IOException
// you'll need to static import the hamcrest matchers referenced below
expected.expect(not(instanceOf(IOException.class));
// call the method under test
callSomething();
}
As you want to fail when exception is NOT an IOException, You can do that by catching the IOException and asserting with fail() like below:
#Test
public void yourTestScenario() {
try {
//code that throws IOException and other Exceptions
} catch(IOException ioexe) {
Assert.fail();
} catch(Exception exe) {
//Ignore
}
}
I get an unhandled Exception type error for the following code, even though, as I understand it, I have handled the exception in the catch block.
class NewException extends Exception{
private String msg;
public NewException(String msg){
this.msg = msg;
}
public String getExceptionMsg(){
return msg;
}}
class CatchException {
public static void method () throws NewException{
try {
throw new NewException("New exception thrown");
}
catch (NewException e){
e.printStackTrace();
System.out.println(e.getExceptionMsg());
}
finally {
System.out.println("In finally");
}
}}
public class TestExceptions{
public static void main(String[] args){
CatchException.method();
}}
Your method() declares that it throws NewException. Whatever is inside that method is irrelevant:
public static void method () throws NewException{
//...
}}
public static void main(String[] args){
CatchException.method();
}}
The compiler sees that you are calling CatchException.method() in main() and that you are not handling it in any way (either catching or declaring main() to throw NewException as well. Thus the error.
The compiler doesn't care if you are actually throwing that exception or not. Have a look at ByteArrayInputStream.close() - there is no way it'll ever throw an IOException - but you still have to handle it since it's declared.
I have some methods which throws some exception, and I want to use AspectJ around advise to calculate the execution time and if some exception is thrown and to log into error log and continue the flow by re-throwing the exception.
I tried to achieve this by following but eclipse says "Unhandled Exception type".
Code-against whom AspectJ is to used :-
public interface Iface {
public void reload() throws TException;
public TUser getUserFromUserId(int userId, String serverId) throws ResumeNotFoundException, TException;
public TUser getUserFromUsername(String username, String serverId) throws ResumeNotFoundException, TException;
public TResume getPartialActiveProfileFromUserId(int userId, int sectionsBitField, String serverId) throws ResumeNotFoundException, UserNotFoundException;
public TResume getPartialActiveProfileFromUsername(String username, int sectionsBitField, String serverId) throws ResumeNotFoundException, UserNotFoundException, TException;
}
Code AspectJ :-
public aspect AspectServerLog {
public static final Logger ERR_LOG = LoggerFactory.getLogger("error");
Object around() : call (* com.abc.Iface.* (..)) {
Object ret;
Throwable ex = null;
StopWatch watch = new Slf4JStopWatch();
try {
ret = proceed();
} catch (UserNotFoundException e) {
ex = e;
throw e;
} catch (ResumeNotFoundException e) {
ex = e;
throw e;
} catch (Throwable e) {
ex = e;
throw new RuntimeException(e);
} finally {
watch.stop(thisJoinPoint.toShortString());
if (ex != null) {
StringBuilder mesg = new StringBuilder("Exception in ");
mesg.append(thisJoinPoint.toShortString()).append('(');
for (Object o : thisJoinPoint.getArgs()) {
mesg.append(o).append(',');
}
mesg.append(')');
ERR_LOG.error(mesg.toString(), ex);
numEx++;
}
}
return ret;
}
}
Please help why this AspectJ is not working.
you can avoid catching the exceptions and just use a try/finally block without the catch.
And if you really need to log the exception you can use an after throwing advice, like this:
public aspect AspectServerLog {
public static final Logger ERR_LOG = LoggerFactory.getLogger("error");
Object around() : call (* com.abc.Iface.* (..)) {
StopWatch watch = new Slf4JStopWatch();
try {
return proceed();
} finally {
watch.stop(thisJoinPoint.toShortString());
}
}
after() throwing (Exception ex) : call (* com.abc.Iface.* (..)) {
StringBuilder mesg = new StringBuilder("Exception in ");
mesg.append(thisJoinPoint.toShortString()).append('(');
for (Object o : thisJoinPoint.getArgs()) {
mesg.append(o).append(',');
}
mesg.append(')');
ERR_LOG.error(mesg.toString(), ex);
}
}
I'm afraid you cannot write advice to throw exceptions that aren't declared to be thrown at the matched join point. Per: http://www.eclipse.org/aspectj/doc/released/progguide/semantics-advice.html :
"An advice declaration must include a throws clause listing the checked exceptions the body may throw. This list of checked exceptions must be compatible with each target join point of the advice, or an error is signalled by the compiler."
There has been discussion on the aspectj mailing list about improving this situation - see threads like this: http://dev.eclipse.org/mhonarc/lists/aspectj-dev/msg01412.html
but basically what you will need to do is different advice for each variant of exception declaration. For example:
Object around() throws ResumeServiceException, ResumeNotFoundException, TException:
call (* Iface.* (..) throws ResumeServiceException, ResumeNotFoundException, TException) {
that will advise everywhere that has those 3 exceptions.
There is an "ugly" workaround - I found them in Spring4 AbstractTransactionAspect
Object around(...): ... {
try {
return proceed(...);
}
catch (RuntimeException ex) {
throw ex;
}
catch (Error err) {
throw err;
}
catch (Throwable thr) {
Rethrower.rethrow(thr);
throw new IllegalStateException("Should never get here", thr);
}
}
/**
* Ugly but safe workaround: We need to be able to propagate checked exceptions,
* despite AspectJ around advice supporting specifically declared exceptions only.
*/
private static class Rethrower {
public static void rethrow(final Throwable exception) {
class CheckedExceptionRethrower<T extends Throwable> {
#SuppressWarnings("unchecked")
private void rethrow(Throwable exception) throws T {
throw (T) exception;
}
}
new CheckedExceptionRethrower<RuntimeException>().rethrow(exception);
}
}