加入以下代码就可以了,注意此类一定要在spring扫描的包下
import com.crm.model.common.ResponseEntity;
import com.crm.model.common.contstants.RequestStatusContants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
public class ApplicationControllerExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(ApplicationControllerExceptionHandler.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResponseEntity handlerError(HttpServletRequest req, Exception e) {
ResponseEntity entity = new ResponseEntity();
entity.setStatus(RequestStatusContants.SERVER_ERROR_ERROR);
entity.setMessage("系统繁忙,请稍后重试");
logger.error("调用" + req.getRequestURI() + "错误", e);
return entity;
}
}
如果以上方法不能进行拦截,可以在BaseController加一个方法
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) {
ModelAndView modelAndView = new ModelAndView();
if (e instanceof BaseException) {
BaseException baseException = (BaseException) e;
modelAndView = buildModelAndView("201", baseException.getMessageText());
} else if (e instanceof OpertionException) {
modelAndView = buildModelAndView("202", e.getMessage());
} else {
modelAndView = buildModelAndView("500", "系统繁忙,请稍后重试");
}
return modelAndView;
}