- 定义异常处理类
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;
}
}
- 定义自定义异常
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;
}
}
- 在springmvc.xml中配置
<bean class="com.company.combine.model.MyCustomerExceptionHanlder"/>
- 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>
- 测试
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("异常了");
}
}
网友评论