springmvc会有一个专门的异常处理器来处理所有的异常情况
项目结构
GlobalExceptionHandler异常处理类
@ControllerAdvice //全局异常处理器
public class GlobalExceptionHandler implements HandlerExceptionResolver {
@ExceptionHandler //该方法处理所有异常的方法
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object arg2,
Exception exception) {
// TODO Auto-generated method stub
Exception e = null;
if(exception instanceof ProductNotException) {
e=exception;
}else {
e=new ProductNotException("未知错误");
}
ModelAndView mav = new ModelAndView();
mav.setViewName("error");
mav.addObject("error",e.getMessage());
return mav;
}
}
ProductController
@Controller
public class ProductController {
@RequestMapping("buy.do")
public ModelAndView buy(Integer id) throws Exception {
if(id==8) {
throw new ProductNotException("商品缺货");
}
return null;
}
}
ProductNotException自定义异常
public class ProductNotException extends Exception{
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public ProductNotException(String message) {
super();
this.message = message;
}
public ProductNotException() {
super();
// TODO Auto-generated constructor stub
}
}