Spring MVC handle Exceptions in Controller using @ExceptionHandler

Points To Remember

  • You can handle all types of runtime exceptions and custom exceptions using @ExceptionHandler annotation. 
  • You just need to define the class to the annotation to handle exceptions of that class.

Spring MVC handle Exceptions in Controller

Here we have a simple Spring MVC application with the following.

  • HomeController wih three actions 
    • throw1 - throws Custom exception
    • throw2 - throws Custom exception
    • throw3 - throws Runtime exception

Home Controller
package com.ekiras.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ekiras.exception.MyException;
import com.ekiras.exception.MyGlobalException;

public class HomeController {
 private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public String home(Locale locale, Model model) {
  logger.info("Welcome home! The client locale is {}.", locale);
  Date date = new Date();
  DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
  String formattedDate = dateFormat.format(date);
  model.addAttribute("serverTime", formattedDate );
  return "home";
 public String throw1(){
  throw new MyException();

 public String throw2(){
  throw new MyGlobalException();

 public String throw3(){
  throw new RuntimeException();

 public String myException(MyException exception){
  return "exception caught message="+ exception.getMessage();

 public String myGlobalException(MyGlobalException exception){
  return "exception caught message="+ exception.getMessage();

The above code will not catch any  Exception of class RuntimeException.  If you want to catch it you can add another method like following to your code.

 public String myGlobalException(Exception exception){
  return "exception caught message="+ exception.getMessage();

Now, after adding the above code to your controller. Your controller will handle all types of Exceptions.

No comments :

Post a Comment