2013-02-03 148 views
2

有沒有辦法處理所有可能的錯誤代碼,同時仍然將代碼傳遞給我的.jsp?在這裏,我有一個單一的錯誤頁面將404添加到模型中。而不是爲每個可能的錯誤代碼添加一個錯誤頁面,是否有更好的方法可以捕獲錯誤並將代碼傳遞給controller/jsp文件?Spring MVC - 動態錯誤處理頁面

控制器

@RequestMapping(value="/error/{code}", method=RequestMethod.GET) 
    public String error(@PathVariable("code") String code, Model model) 
    { 
     model.addAttribute("code", code); 
     return "error"; 
    } 

的web.xml

<error-page> 
    <error-code>404</error-code> 
    <location>/error/404</location> 
</error-page> 

回答

1

你可以在Spring註冊一個通用的異常解析器來捕獲所有異常,並變身爲你error.jsp的呈現。

使用你的業務邏輯拋出一個專門的RuntimeException,具有code成員:

public class MyException extends RuntimeException { 
    private final Integer errorCode; 

    public MyException(String message, Throwable cause, int errorCode) { 
     super(message, cause); 
     this.errorCode = errorCode; 
    } 
} 

或者依賴於異常消息現有RuntimeException的情況下與你code

提取code和/或消息並相應地設置HttpServletResponse狀態和ModelAndView。

例如:

import org.springframework.stereotype.Component; 
import org.springframework.web.servlet.DispatcherServlet; 
import org.springframework.web.servlet.HandlerExceptionResolver; 
import org.springframework.web.servlet.ModelAndView; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

@Component(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME) 
public class GenericHandlerExceptionResolver implements HandlerExceptionResolver { 

    @Override 
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) { 
     ModelAndView mav = new ModelAndView("error"); 

     if (e instanceof MyException) { 
      MyException myException = (MyException) e; 
      String code = myException.getCode(); 

      // could set the HTTP Status code 
      response.setStatus(HttpServletResponse.XXX); 

      // and add to the model 
      mav.addObject("code", code); 
     } // catch other Exception types and convert into your error page if required 

     return mav; 
    } 
}