一种方法是使用HandlerExceptionResolver
接口。
HandlerExceptionResolver 接口的替代方法是@ExceptionHandler
注解。您使用控制器中的@ExceptionHandler
方法注释来指定在执行控制器方法期间抛出特定类型的异常时调用哪个方法。例如:
package com.spring3;
import org.springframework.stereotype.Controller;
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.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloWorldController {
@ExceptionHandler(Exception.class)
public ModelAndView handleMyException(Exception exception) {
ModelAndView mv = new ModelAndView("redirect:errorMessage.html?error=" + exception.getMessage());
return mv;
}
@RequestMapping(value = "/errorMessage", method = RequestMethod.GET)
public ModelAndView handleMyExceptionOnRedirect(@RequestParam("error") String error) {
ModelAndView mv = new ModelAndView("uncaughtExceptionSpring");
v.addObject("error", error);
return mv;
}
@RequestMapping("/hello")
public ModelAndView helloWorld() throws Exception {
String message = "Hello World, Spring 3.0!";
return new ModelAndView("hello", "message", message);
}
}
Spring MVC 异常处理和显示自定义视图Part1 , 2 , 3 , 4