简体   繁体   中英

spring rest exception in service

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM