一、写一个自定义异常类,继承Exception。
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
二、写一个全局异常处理器,实现HandlerExceptionResolver接口,并且作为Bean注册到Spring。
@Component
public class ExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {
CustomException customException;
if (ex instanceof CustomException) {
customException = (CustomException) ex;
} else {
customException = new CustomException("未知异常:" + ex.getMessage());
}
customException.printStackTrace(System.out);
ModelAndView mav = new ModelAndView();
mav.addObject("errorMsg", customException.getMessage());
mav.setViewName("/error");
return mav;
}
}
三、异常类应用
在controller、service、dao中任意一处需要手动抛出异常。
如果与业务功能相关的异常,建议在service中抛出异常。
与业务功能没有关系的异常,建议在controller中抛出。