DEV Community

Cover image for Overcoming Challenges While Migrating from JDK 8 to JDK 17: Resolving Custom Exception Issues
Shalini Tv
Shalini Tv

Posted on

Overcoming Challenges While Migrating from JDK 8 to JDK 17: Resolving Custom Exception Issues

As Java constantly evolves, many developers are contemplating the shift from JDK 8 to JDK 17. This transition offers improved performance, increased stability, and a wealth of new features. Nevertheless, the process is not always seamless and presents several challenges. This article spotlights one such issue related to exception handling.

Recently, I undertook the task of migrating from JDK 8 to JDK 17. My toolkit included Gradle as the build tool, Java 17, and Spring Boot. Among the various challenges I faced, the primary focus of this post is an issue related to exception handling.

Have you ever expected a custom exception message format but the application throws the default exception message? Let's delve into this.

In Spring Boot, when a request processing results in an exception, the application usually returns a default error view (for browser clients) or a JSON response (for REST clients) with the following structure:

{
"timestamp": "2022-03-25T13:01:02.000+0000",
"status": 500,
"error": "Internal Server Error",
"message": "An error occurred",
"path": "/api/endpoint"
}

However, at times, you might expect the format to be something like this:

{
"errors":[
{
"code":"API_ERROR_403",
"message":
"error message"
}
]

}

The Solution:

The core of the issue lies in the significant changes introduced with respect to tomcat-embed version. The javax.servlet.http.HttpServletRequest has been replaced by jakarta.servlet.http.HttpServletRequest. The solution is to replace all javax imports with jakarta, and your application should run smoothly.

The tricky part is that you might not encounter import errors if your gradle/maven build file includes the javax.servlet.api dependency. It would import it from javax.servlet.api, but it won't function as expected due to conflicts between the jakarta APIs from the tomcat.embed version and javax.servlet.api.

Therefore, if you aim to use Tomcat 10, you must migrate your code to use the jakarta. packages. If, for some reason, this change is not feasible, it's advisable to stick to Tomcat 9 or earlier versions, which continue to use the javax. packages.

It's important to note that including both javax. and jakarta. libraries in your project can lead to conflicting classes and unpredictable behavior, and is generally discouraged.

Thank you for reading this post. Happy coding!``

Top comments (0)