1 项目中常常出现遇到RuntimeException,须要给出一个默认返回JSONjava
2 使用 @ControllerAdvice,不用任何的配置,只要把这个类放在项目中,Spring能扫描到的地方。就能够实现全局异常的回调。web
代码以下:spring
package cc.messcat.common.exception;数据库 import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.ControllerAdvice; import cc.messcat.common.constant.CommonConstant; import com.alibaba.fastjson.support.spring.FastJsonJsonView;this
/**
} |
BizException定义:
package cc.messcat.common.exception; /** private static final long serialVersionUID = -5875371379845226068L; /** /** /** /** /** /** /** /** public BizException(int code, String msgFormat, Object... args) { public BizException() { public String getMsg() { public int getCode() { /** public BizException(String message, Throwable cause) { public BizException(Throwable cause) { public BizException(String message) { |
BaseException定义:
/** import org.apache.commons.logging.Log; /** private static final long serialVersionUID = 662981704729484572L; private static final Log log = LogFactory.getLog(BaseException.class); /** public BaseException(int code, String msgFormat, Object... args) { public BaseException(int code, String msg) { /** public BaseException print() { |
调用例子:
Route route = routeTravelAppService.getRouteInfo(routeId); if(route == null ){ throw new BaseException(BaseException.TICKET_NOTE_TYPE_IS_NOT_AVAILABLE,"行程为空"); } |