springmvc框架采用的是统一、全局的异常处理。把controller中的所有异常处理都集中到一个地方。采用的是AOP的思想、把业务逻辑和异常处理代码分开,降低耦合。Springmvc中的异常处理主要用到以下两个注解@ControllerAdvice和@ExceptionHandler。
1、自定义1个异常类。
public class LzsException extends RuntimeException {
private static final long serialVersionUID = 9053285379587890690L;
protected int errCode;
protected String errMsg;
protected Throwable errCause;
public LzsException() {
super();
}
public LzsException(String errMsg) {
super(errMsg);
this.errMsg = errMsg;
}
public LzsException(Throwable errCause) {
super(errCause);
this.errCause = errCause;
}
public LzsException(String errMsg, Throwable errCause) {
super(errMsg,errCause);
this.errMsg = errMsg;
this.errCause = errCause;
}
public LzsException(int errCode, Throwable errCause) {
super();
this.errCode = errCode;
this.errCause = errCause;
}
}
2、定义个普通类,作为全局异常处理类
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(Exception.class)
@ResponseBody
public HttpJsonResponse exceptionHandler(Exception e){
log.error("Exception:{}",e.getMessage());
HttpJsonResponse result = new HttpJsonResponse();
result.setCode(ResponseConst.ErrorCode.ERR_999);
result.setMessage("服务器内部错误,请联系管理员");
return result;
}
@ExceptionHandler(LzsException.class)
@ResponseBody
public HttpJsonResponse lzsExceptionHandler(Exception e){
log.error("LzsException异常:{}",e.getMessage());
HttpJsonResponse result = new HttpJsonResponse();
result.setCode(ResponseConst.ErrorCode.ERR_999);
result.setMessage(e.getMessage());
//1可以吧异常信息记录下来保存到数据库,
//2发送通知,把异常信息通过邮件,短信,微信发给相关人员。
//3返回前端友好提示
return result;
}
}
3、通过Controller调用service层业务接口,service层抛出异常:
if (CollectionUtils.isEmpty(unionIdList)) {
throw new LzsException("请联系管理员设置xxx");
}
4、如果没起作用,可以排查以下两个方便。
4.1检查是否在配置文件application.xml里有这样的配置,如果没有需要加上:
<mvc:annotation-driven /> <context:component-scan base-package="com.lzs" />
4.2 检查controller层是否加了try...catch .有则去掉