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,"行程爲空"); } |