Skip to main content

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;

@Controller
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";
}

@RequestMapping(value="/throw1")
public String throw1(){
throw new MyException();
}


@RequestMapping(value="/throw2")
public String throw2(){
throw new MyGlobalException();
}

@RequestMapping(value="/throw3")
public String throw3(){
throw new RuntimeException();
}



@ResponseBody
@ExceptionHandler(MyException.class)
public String myException(MyException exception){
return "exception caught message="+ exception.getMessage();
}

@ResponseBody
@ExceptionHandler(MyGlobalException.class)
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.


@ResponseBody
@ExceptionHandler(Exception.class)
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.

Comments