CustomException 异常类
package com.xmx.config;
public class CustomException extends Exception {
private static final long serialVersionUID = 1L;
public String message;
public Throwable throwable;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Throwable getThrowable() {
return throwable;
}
public void setThrowable(Throwable throwable) {
this.throwable = throwable;
}
public CustomException(String message) {
super();
this.message = message;
}
public CustomException(Throwable throwable) {
super();
this.throwable = throwable;
}
}
CustomExceptionResolver.java
package com.xmx.config;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CustomExceptionResolver implements HandlerExceptionResolver {
@ExceptionHandler(Exception.class)
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
CustomException customException = null;
String message = "";
if(ex instanceof CustomException){
customException = (CustomException)ex;
message = customException.getMessage();
}
else{
customException = new CustomException("操作错误");
message = customException.getMessage();
}
System.out.println("发生错误了,错误信息如下:");
System.out.println(ex);
System.out.println();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message",message);
modelAndView.setViewName("error");
return modelAndView;
}
}
在springmvc配置文件中加入全局异常配置
<!--全局异常配置-->
<bean id="exceptionResolver" class="com.xmx.config.CustomExceptionResolver"></bean>