美文网首页ssm
SpringMVC 异常处理<9>

SpringMVC 异常处理<9>

作者: 天空在微笑 | 来源:发表于2017-08-17 23:59 被阅读6次
    1. 定义异常处理类
    package com.company.combine.model;
    
    import org.springframework.web.method.annotation.ExceptionHandlerMethodResolver;
    import org.springframework.web.servlet.HandlerExceptionResolver;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
    * Created by liuqun on 2017/8/16.
    */
    public class MyCustomerExceptionHanlder implements HandlerExceptionResolver {
       @Override
       public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
           ModelAndView modelAndView = new ModelAndView();
           if (e instanceof MyCustomerException) {
               modelAndView.addObject("error", "MyCustomerException"+((MyCustomerException) e).getMsg());
           }else{
               modelAndView.addObject("error", "Exception"+e.getMessage());
           }
           modelAndView.setViewName("error");
           return modelAndView;
       }
    }
    
    1. 定义自定义异常
    package com.company.combine.model;
    
    /**
     * Created by liuqun on 2017/8/16.
     */
    public class MyCustomerException extends Exception {
        private String msg;
    
        public MyCustomerException(String msg) {
            super(msg);
            this.msg = msg;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    }
    
    1. 在springmvc.xml中配置
    <bean class="com.company.combine.model.MyCustomerExceptionHanlder"/>
    
    1. error.jsp
    <%--
      Created by IntelliJ IDEA.
      User: liuqun
      Date: 2017/7/31
      Time: 21:59
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title>环境配置</title>
      </head>
      <body>
      ${error}
      </body>
    </html>
    
    1. 测试
    package com.company.combine.controller;
    
    import com.company.combine.model.MyCustomerException;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /**
     * Created by liuqun on 2017/8/16.
     */
    @Controller
    public class ExceptionTestController {
        @RequestMapping(value = "requestError")
        public void testException() throws MyCustomerException {
           throw new MyCustomerException("异常了");
    
        }
    }
    

    相关文章

      网友评论

        本文标题:SpringMVC 异常处理<9>

        本文链接:https://www.haomeiwen.com/subject/sclorxtx.html