SpringMvc中的统一异常处理器

来源:互联网 发布:淘宝乐优软件好用吗 编辑:程序博客网 时间:2024/06/13 15:56

一般项目中都需要作异常处理,基于系统架构的设计考虑,使用统一的异常处理方法,这些异常有可能是预期的可能发生的,这个时候我们可以捕获它,但是也有一些异常是运行时才会发生的,我们无从捕获它,此时也需要统一的异常处理

在SpringMVC中我们需要可以自定义一个(一般为多个)异常类,遇到可以预期的异常是的时候,捕获相应的自定义的异常,遇到运行时产生的异常的时候,在统一的异常处理器中捕获,实现统一的异常处理,需要实现一个接口HandlerExceptionResolver,并在spring容器中注册

public class CustomerException extends Exception {    private String message;    public String getMessage() {        return message;    }    public void setMessage(String message) {        this.message = message;    }    public CustomerException(String message) {        super();        this.message = message;    }}
public class CustomerExceptionResolver implements HandlerExceptionResolver{    @Override    public ModelAndView resolveException(HttpServletRequest request,            HttpServletResponse response, Object handler, Exception ex) {        ModelAndView modelAndView = new ModelAndView();        ex.printStackTrace();        CustomerException customerException = null;        if(ex instanceof CustomerException){            customerException = (CustomerException)ex;        }else{            customerException = new CustomerException("未知的错误");        }        String message = customerException.getMessage();        request.setAttribute("message", message);        try {            request.getRequestDispatcher("/WEB-INF/view/error.jsp").forward(request, response);        } catch (ServletException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return modelAndView;    }}
    <!-- 配置异常处理器 -->    <bean class="com.njust.ssm.exception.resolver.CustomerExceptionResolver"></bean>
原创粉丝点击