springmvc的全局异常处理
package org.springframework.web.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface HandlerExceptionResolver {
ModelAndView resolveException(HttpServletRequest var1, HttpServletResponse var2, Object var3, Exception var4);
}
仔细观察这个接口, 我们发现这个接口返回类型是ModelAndView,也就是说当出现异常时,我们可以以一个界面来展现给用户,让我们的网站设计的更加友好。 现在我们通过编写具体的实现类
package com.hy.exception;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @Author: Han Yu
* @Description:
* @Date: Create in 13:24 2019/2/23
*/
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
String result = "发生异常请联系管理员";
if(e instanceof CustomDemoException){
result = ((CustomDemoException)e).getErroeMsg();
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("result",result);
modelAndView.setViewName("error/error");
return modelAndView;
}
}
上面这段代码仔细阅读可以发现一个CustomDemoException类,这个类的作用呢就是我们的自定义异常,我们可以对于无法用原来的异常处理的异常编写自定义异常处理类,而且可以编写多个,这里编写了一个作为列子
package com.hy.exception;
/**
* @Author: Han Yu
* @Description:
* @Date: Create in 13:39 2019/2/23
*/
public class CustomDemoException extends Exception {
private String erroeMsg;
public CustomDemoException(){
super();
}
public CustomDemoException(String erroeMsg) {
super();
this.erroeMsg = erroeMsg;
}
public String getErroeMsg() {
return erroeMsg;
}
public void setErroeMsg(String erroeMsg) {
this.erroeMsg = erroeMsg;
}
}
最重要的一步,我们需要在springmvc.xml配置文件中写一个bean,这个bean就是springmvc给我们提供的HandlerExceptionResolver接口的实现类
<!--异常处理 全局异常 一个系统就一个-->
<!--配置全局异常处理器-->
<bean class="com.hy.exception.CustomExceptionResolver"/>
这样springmvc就可以加载这个类,判断他是实现的接口而知道这是一个全局异常处理器。
@RequestMapping("/index")
public String fmdIndex() throws Exception{
// int i=1/0;
if(true){
throw new CustomDemoException("你好 自定义异常");
}
return "Login/Index";
}