Reputation: 139
I am implementing a spring rest application as a maven multi module project. controllers in web, service and dao as layers.
I am having issues to find the exact cause and stack trace for any exception in service layer. I am not using any try catch block in the service methods. Instead, I am just throwing an exception. Now when a null pointer exception is raised, the global exception handler is finding the exception. It says null, but does not provide any stack trace.
Do I need to use try catch blocks? If yes, I will have these blocks all over the service methods.
Any suggestions are welcome.
Upvotes: 1
Views: 687
Reputation: 73578
Your exception handler isn't displaying the stacktrace because you're not telling it to. Your code is bad and broken.
logger.error("Error: " + e.getMessage());
logger.error("Error [cause]: " + e.getCause());
Using getMessage()
to see what exception you're having is useless. A NullPointerException
returns as its message the String "null"
, which doesn't help you solve problems one bit. Logging the cause like that will call the toString()
method of cause
which won't be helpful either.
The only way to deal with exceptions is:
logger.error("Error", e);
This will log the stacktrace properly, including any causes (your code didn't even consider that a cause can also have a cause). You can use a custom message instead of "Error", but it doesn't really matter.
Upvotes: 1
Reputation: 244
You can use @ExceptionHandler. Here you'll find some examples and see that dont need to modify your current code. Remember to use a Logger or put a System.out.printLn() to see the stacktrace of the exception. Also maybe you have to consider debug your method to see waht parameter or method is givin a null value.
Upvotes: 0