Authored by sailing-PC\sailing

add

package com.yohoufo.common.controller.exceptionhandler;
import com.yoho.core.common.utils.HttpRequestUtils;
import com.yoho.error.ServiceError;
import com.yoho.error.exception.ServiceException;
import com.yoho.error.exception.handler.ServiceGlobalExceptionHandler;
import com.yohoufo.common.exception.GatewayException;
import com.yohoufo.common.exception.SessionExpireException;
import com.yohoufo.common.utils.ServletUtils;
import org.apache.commons.httpclient.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.UnsatisfiedServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.MessageFormat;
import java.util.Map;
/**
* Gateway全局异常处理。
* @author chunhua.zhang@yoho.cn
*
* 如果是 #{@link ServiceException} 或者 #{@link GatewayException}, 则返回200,并且返回json消息体
*
*/
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
private static String YH_ERR_CODE_HEADER="X-YH-Code";
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
final String serviceName = ServletUtils.getServiceName(request);
final Map<String, Object> params = HttpRequestUtils.getRequestParams(request);
response.addHeader(YH_ERR_CODE_HEADER,"500");
//用户未登录,或登录 会话超时
if( e instanceof SessionExpireException){
log.info("session expire at url:{}, params:{}", serviceName, params);
response.setStatus(401);
return new ModelAndView();
}
//如果是请求URL匹配不了,则返回400
if(e instanceof UnsatisfiedServletRequestParameterException){
log.warn("can not find validate request mapping at {}", request.getRequestURI());
response.setStatus(HttpStatus.SC_BAD_REQUEST);
return new ModelAndView();
}
//如果是业务异常,则返回http 200,并且构造json消息体中错误码&错误内容
if (e instanceof GatewayException || e instanceof ServiceException) {
int code;
String desc;
if (e instanceof GatewayException) {
code = ((GatewayException) e).getErrorCode();
desc = ((GatewayException) e).getDesc();
} else { //服务异常,不能直接返回给客户端,必须映射一下
ServiceException serviceException = (ServiceException) e;
ServiceError serviceError = serviceException.getServiceError();
code = serviceError.getMappingGatewayError().getLeft();
desc = serviceError.getMappingGatewayError().getRight();
if (serviceException.getParams() != null) {
desc = MessageFormat.format(desc, serviceException.getParams());
}
}
log.warn("service exception happened at:{}, code:{}, desc:{}, uri:{}, request: {}, params is: {}", serviceName, code, desc, request.getRequestURI(), serviceName, params);
ModelAndView mv = ServiceGlobalExceptionHandler.getErrorJsonView(code, desc);
return mv;
}
log.warn("gateway other exception happened at uri:{}, request: {}, params is: {}, e is:{}", request.getRequestURI(), serviceName, params, e);
//其他异常,返回500
response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
return new ModelAndView();
}
}
\ No newline at end of file
... ...
package com.yohoufo.common.http;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* Created by chenchao on 2018/9/14.
*/
@Component
public class URLHolder {
private String protocol = "http";
private String domain_local = "localhost";
private int port = 8080;
@Value("${web.context}")
private String contextPath;
private String url;
@PostConstruct
public void buildUrl(){
this.url = new StringBuilder(protocol).append("://").append(domain_local).append(":").append(port)
.append("/").append(contextPath).toString();
}
public String getUrl() {
return url;
}
}
... ...
package com.yohoufo.common.utils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* Created by chunhua.zhang@yoho.cn on 2015/12/15.
*/
public class BigDecimalHelper {
public static final String FORMAT_TWOBITAFTERPOINT = "###.00";
private static Map<String,DecimalFormat> DecimalFormatCache = new HashMap<>();
static {
DecimalFormatCache.put(FORMAT_TWOBITAFTERPOINT, new DecimalFormat(FORMAT_TWOBITAFTERPOINT));
}
public static DecimalFormat getDecimalFormat(String format){
final String key = format;
final Map<String,DecimalFormat> cache = DecimalFormatCache;
DecimalFormat decimalFormat ;
if (Objects.isNull(decimalFormat = cache.get(key))){
cache.put(key, (decimalFormat = new DecimalFormat(format)));
}
return decimalFormat;
}
public static String formatNumber(Number number, String format){
return getDecimalFormat(format).format(number);
}
/**
* to double
* @return double
*/
public static double round(BigDecimal toRound){
DecimalFormat df = new DecimalFormat("0.00");
df.setRoundingMode(RoundingMode.DOWN);
return Double.valueOf(df.format(toRound));
}
/**
* to double
* @param bigDecimal
* @return double
*/
public static double toDouble(BigDecimal bigDecimal){
DecimalFormat df = new DecimalFormat("0.00");
df.setRoundingMode(RoundingMode.DOWN);
return Double.valueOf(df.format(bigDecimal.doubleValue()));
}
/**
* to double
* @param bigDecimal
* @return double
*/
public static BigDecimal up(BigDecimal bigDecimal){
DecimalFormat df = new DecimalFormat("0.00");
df.setRoundingMode(RoundingMode.UP);
return new BigDecimal(df.format(bigDecimal.doubleValue()));
}
public static double upDouble(BigDecimal bigDecimal) {
DecimalFormat df = new DecimalFormat("0.00");
df.setRoundingMode(RoundingMode.UP);
return Double.valueOf(df.format(bigDecimal.doubleValue()));
}
}
... ...
package com.yohoufo.common.utils;
/**
* Created by chenchao on 2018/9/14.
*/
public class PriceFormater {
public static final String CURRENCYSYMBOL_ZH = "¥";
public static String addCnCurrencySymbol(String price){
return CURRENCYSYMBOL_ZH + price;
}
}
... ...
... ... @@ -3,6 +3,7 @@ package com.yohoufo.order.controller;
import com.yohobuy.ufo.model.order.bo.SoldPrdComputeBo;
import com.yohobuy.ufo.model.order.req.SellerOrderComputeReq;
import com.yohoufo.common.ApiResponse;
import com.yohoufo.common.exception.GatewayException;
import com.yohoufo.order.service.SellerOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
... ... @@ -26,7 +27,7 @@ public class SellerOrderController {
@RequestMapping(params = "method=ufo.sellerOrder.computePublishPrd")
public ApiResponse computePublishPrd(@RequestParam(name = "uid", required = true)int uid,
@RequestParam(name = "storage_id", required = true)int storage_id,
@RequestParam(name="price", required = true)String price){
@RequestParam(name="price", required = true)String price) throws GatewayException {
SellerOrderComputeReq req = SellerOrderComputeReq.builder().uid(uid).storageId(storage_id).price(price).build();
SoldPrdComputeBo computeBo = sellerOrderService.computePublishPrd(req);
... ...
package com.yohoufo.order.service;
import com.yoho.core.rest.client.ServiceCaller;
import com.yoho.core.rest.client.hystrix.AsyncFuture;
import com.yohobuy.ufo.model.order.bo.PlatformFee;
import com.yohobuy.ufo.model.order.bo.SoldPrdComputeBo;
import com.yohobuy.ufo.model.order.req.SellerOrderComputeReq;
import com.yohoufo.common.exception.GatewayException;
import com.yohoufo.common.http.URLHolder;
import com.yohoufo.order.dal.SellerOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
/**
* Created by chenchao on 2018/9/13.
*/
... ... @@ -21,11 +28,42 @@ public class SellerOrderService {
@Autowired
private ServiceCaller serviceCaller;
@Autowired
private URLHolder urlHolder;
public SoldPrdComputeBo computePublishPrd(SellerOrderComputeReq req){
public SoldPrdComputeBo computePublishPrd(SellerOrderComputeReq req) throws GatewayException {
log.info("in computePublishPrd, req {}", req);
SoldPrdComputeBo computeBo = null;
//TODO
String baseUrl = urlHolder.getUrl();
String apiParam = "?method=ufo.product.storage.leastprice";
String fullUrl = baseUrl + apiParam;
Object params = new Object();
AsyncFuture<Object> future = serviceCaller.post("product.getFloorPrice", fullUrl, params, Object.class, new Object());
Object resp = future.get();
/*商品鉴定费 ¥10.00
商品包装费 ¥10.00
平台服务费(5%,优惠期间0%) ¥0.00
*/
String price = req.getPrice();
if (StringUtils.isBlank(price)){
log.warn("in computePublishPrd price illegal , req {}", req);
throw new GatewayException(400, "没有价格");
}
try{
BigDecimal prdPrice = new BigDecimal(price);
String earnestMoneyStr;
PlatformFee platformFee;
String incomeStr;
//保证金(28-200(按照卖家发布商品的货款金额5%计算,最低28,封顶200));
}catch (Exception e){
log.warn("in computePublishPrd price convert BigDecimal fail, {}", req);
}
return computeBo;
}
... ...