Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Error Handling Mechanisms in Spring MVC

Tech 2

Spring MVC applications categorize errors into two types: checked exceptions and runtime exceptions. Checked exceptions are typical handled via try-catch blocks, while runtime excpetions are minimized through robust coding practices and testing. When exceptions occur in DAO, service, or controller layers, they propagate upward via throws declarations. The Spring MVC front controller eventually delegates these exceptions to configured exception handlers.

Method 1: Local Controller Exception Handling with @ExceptionHandler

This approach only manages exceptions originating from the same controller class where the handler is defined.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class DemoControllerA {
    @RequestMapping("/calculate")
    public String performCalculation() {
        int result = 5 / 0;
        return "resultView.jsp";
    }
    
    @RequestMapping("/processString")
    public String stringOperation() {
        String text = null;
        int length = text.length();
        return "resultView.jsp";
    }
    
    @ExceptionHandler({ArithmeticException.class, NullPointerException.class})
    public ModelAndView handleControllerErrors() {
        ModelAndView errorView = new ModelAndView();
        errorView.setViewName("errorPage.jsp");
        return errorView;
    }
}

Method 2: Global Exception Handling with @ControllerAdvice

This handler provides application-wide exception management but has lower priority than controller-local @ExceptionHandler methods.

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class ApplicationExceptionHandler {
    @ExceptionHandler({ArithmeticException.class, NullPointerException.class})
    public ModelAndView handleGlobalExceptions() {
        ModelAndView errorModel = new ModelAndView();
        errorModel.setViewName("applicationError.jsp");
        return errorModel;
    }
}

Include the handler package in component scanning:

<context:component-scan base-package="com.example.service,com.example.exception" />

Method 3: Configuration-Based Exception Resolution

XML Configuraton Using SimpleMappingExceptionResolver

<bean id="globalExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="java.lang.ArithmeticException">redirect:/mathError.jsp</prop>
            <prop key="java.lang.NullPointerException">redirect:/nullError.jsp</prop>
        </props>
    </property>
</bean>

Java Configuration Approach

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import java.util.Properties;

@Configuration
public class ExceptionResolverConfig {
    @Bean
    public SimpleMappingExceptionResolver createExceptionResolver() {
        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
        Properties mapping = new Properties();
        mapping.put("java.lang.NullPointerException", "nullPointerView.jsp");
        mapping.put("java.lang.ArithmeticException", "arithmeticView.jsp");
        resolver.setExceptionMappings(mapping);
        return resolver;
    }
}

Method 4: Custom Exception Resolver Implementation

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class CustomExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest req, 
                                         HttpServletResponse res, 
                                         Object handler, 
                                         Exception exc) {
        ModelAndView modelView = new ModelAndView();
        if (exc instanceof NullPointerException) {
            modelView.setViewName("nullErrorView");
        } else if (exc instanceof ArithmeticException) {
            modelView.setViewName("arithmeticErrorView");
        }
        modelView.addObject("errorMessage", exc.toString());
        return modelView;
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.