DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • A Systematic Approach for Java Software Upgrades
  • From J2EE to Jakarta EE
  • Exploring Exciting New Features in Java 17 With Examples
  • The Next Evolution of Java: Faster Innovation, Simpler Adoption

Trending

  • AI Meets Vector Databases: Redefining Data Retrieval in the Age of Intelligence
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • Hybrid Cloud vs Multi-Cloud: Choosing the Right Strategy for AI Scalability and Security
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  1. DZone
  2. Coding
  3. Java
  4. Java EE 8 MVC: Global Exception Handling

Java EE 8 MVC: Global Exception Handling

Adding global exception handling to an Java EE MVC application is quite simple.

By 
Michael Scharhag user avatar
Michael Scharhag
·
May. 13, 16 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
12.0K Views

Join the DZone community and get the full member experience.

Join For Free

In the previous posts we learned about various ways to access request information (e.g. query or path parameters) in Java EE MVC. This post shows how to apply global exception handling to an MVC application.

Assume we have a controller method that might throw an IllegalArgumentException:

@Controller
@Path("illegal-argument")
public class ExceptionController {

  @GET
  public String doWork() {
    // code that might throw an IllegalArgumentException
  }

}


We could now add a try/catch block to doWork() and wrap the piece of code that might throw the exception. However, this approach becomes tedious if it needs to be applied to multiple methods.

In such a case we can register a global exception mapper. To do this, we have to create a class that implements the generic ExceptionMapper interface.

A simple ExceptionMapper for IllegalArgumentExceptions looks like this:

@Provider
public class IllegalArgumentExceptionMapper implements ExceptionMapper<IllegalArgumentException> {

  @Inject
  private Models models;

  @Override
  public Response toResponse(IllegalArgumentException exception) {
    models.put("message", exception.getMessage());

    return Response.status(Response.Status.BAD_REQUEST)
        .entity("/WEB-INF/jsp/error.jsp")
        .build();
  }
}


Now, whenever an IllegalArgumentException is thrown from controller methods, IllegalArgumentExceptionMapper will be used to convert the exception to an appropriate response. Here a simple error view (error.jsp) is rendered.

If you want a generic ExceptionMapper that handles all types of exceptions, you simply have to implement ExceptionMapper<Exception>. If you have multiple ExceptionMapper implementations that are suitable to handle a thrown exception, the most specific ExceptionMapper is used.

Quick Summary

Adding global exception handling to an Java EE MVC application is quite simple. We only have to create a class that implements the ExceptionMapper interface with the exception type that should be handled.

The full example code can be found on GitHub.

Java EE Java (programming language)

Published at DZone with permission of Michael Scharhag, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A Systematic Approach for Java Software Upgrades
  • From J2EE to Jakarta EE
  • Exploring Exciting New Features in Java 17 With Examples
  • The Next Evolution of Java: Faster Innovation, Simpler Adoption

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!