Spring MVC ExceptionHandling:注释为@ExceptionHandling的操作无法将变量传递给错误视图

时间:2013-03-06 15:24:14

标签: spring java-ee web-applications spring-mvc exception-handling

我知道很多人都有类似的问题。再次发布,但我相信我可能做得不好。

我将Spring 3.0.5freemarker 2.3.14一起使用。基本上我想向用户显示友好的错误消息。

@Controller("exceptioncontroller")
public class ExceptionController {
private static Logger logger = Logger.getLogger(ExceptionController.class);

@RequestMapping(value = "/site/contentnofoundexception")
public String throwContentFileNotFound(){
    boolean exception = true;
    if(exception){
        throw new ContentFileNotFoundException("content ZZZ123 not found");
    }
    return  "errortest";
}


@ExceptionHandler(value = ContentFileNotFoundException.class)
public String handleFileNotFoundException(ContentFileNotFoundException ex, Model model) {
    model.addAttribute("msg",ex.getErrorMessage());//this message is never passed to the error view. msg is always null 
    return "error";
 }
}


//same issue for handleException action which uses ModelAndView
@ExceptionHandler(value = Exception.class)
public ModelAndView handleException(Exception ex){
   logger.error(ex);
    ModelAndView mv = new ModelAndView();
    mv.setViewName("error");
    String message = "Something Broke. Please try again later";
    mv.addObject("msg", message);
    return mv;
} 

 // Custom Exception class   
 public class ContentFileNotFoundException extends RuntimeException {

 private String errorMessage;

 public ContentFileNotFoundException(String message) {
    this.setErrorMessage(message);
 }

 public String getErrorMessage() {
    return errorMessage;
 }

 public void setErrorMessage(String errorMessage) {
     this.errorMessage = errorMessage;
 }
}

因此,每个案例都可以调用handleFileNotFoundExceptionhandleException个操作,但他们无法向error.ftl视图发送任何消息以显示给用户。我需要配置什么吗?

感谢您提前帮助

0 个答案:

没有答案