//编写自定义异常类 package cn.bdqn.stusystem.util; public class MyException extends Exception{ private String message; public MyException(String message) { this.message = message; } public MyException() { } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } //实现异常处理器 package cn.bdqn.stusystem.util; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; public class MyHandleException implements HandlerExceptionResolver{ @Override public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) { // 定义异常信息 String msg; // 判断异常类型 if(arg3 instanceof MyException){ msg = arg3.getMessage(); }else{ Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); arg3.printStackTrace(printWriter); msg = writer.toString(); } ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("msg", msg); modelAndView.setViewName("error"); return modelAndView; } } //在springmvc中配置异常处理器 <bean id="myHandleException" class="cn.bdqn.stusystem.util.MyHandleException"></bean>
原文地址:https://www.cnblogs.com/ZhangHaiBK/p/8988699.html
时间: 2024-11-13 16:58:29