系统中一般有controller/service/dao三层,当出现异常时,向上抛出,最后由springmvc的前端控制器交给异常处理器。
- 自定义异常
public class CustomException extends Exception{
private String message;
public CustomException(String message){
this.message = message;
}
public String getMessage(){
return message;
}
}
- 抛出该异常
@GetMapping("/exception")
public String exception() throws CustomException {
throw new CustomException("抛出了custom异常");
}
- 自定义异常处理器
public class CustomExceptionResolver implements HandlerExceptionResolver{
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
CustomException custom = null;
if(e instanceof CustomException){
custom = (CustomException) e;
}else{
custom = new CustomException("不是custom异常");
}
System.out.println(custom.getMessage());
return null;
}
}
- 注册自定义异常处理器
<bean id="handlerExceptionResolver" class="com.kuang.exception.CustomExceptionResolver"/>
这样当出现异常时,就会被自定义的异常处理器处理了。