DubboX参数验证失败的返回错误信息的格式转换和时间参数序列化的问题解决

Dubbox中的参数验证失败返回信息的格式问题

在使用dubbox进行实际项目开发的过程中,对输入的参数进行验证是一个很常见的问题,所以在Dubbo中提供了参数化验证的机制。但是,在具体项目实施的过程中,发现当参数验证失败的时候,返回的结果数据是一个xml格式的文本,而我们的客户端所接受的数据均为json格式,那我们怎么做这样一个格式转换呢?其实,可以采用两种方式进行解决,一种是扩展一个Dubbo的调用拦截,写一个扩展类(如下所示)实现Filter接口,并在调用的invoke方法中捕获参数验证失败的异常,然后对异常结果进行处理,返回json格式的错误信息;

 public class ValidationExceptionFilter implements Filter{

public Result  invoke(Invoker<?> invoker, Invocation invocation){

Result result = null;

BaseDTO resDto = new BaseDTO();

try{

result = invoker.invoke(invocation);

}catch(RpcException e){

ConstraintViolationException ve = (ConstraintViolationException ) e.getCause();

Set<ConstraintViolation<?>> violations = ve.getConstraintVoilations();

String resultMsg = “”;

for(ConstraintViolation<?> constraintViolation : violations){

String errorMsg = constraintViolation.getMessage();

String property = constraintViolation.getProperty.toString();

resultMsg = resultMsg + property + ":" + errorMsg + "; ";

}

resDto.setSuccess(false);

resDto.setMessage(resultMsg);

return new RpcResult(resDto);

}

return result;

}

}

 

另一种方式是通过直接继承dubbo rest的RpcExceptionMapper,并覆盖其中处理校验异常的方法即可,具体如下所示:

public class MyValidationExceptionMapperextends RpcExceptionMapper {

   protected ResponsehandleConstraintViolationException(ConstraintViolationException cve) {

       ViolationReport report = new ViolationReport();

       for (ConstraintViolation cv : cve.getConstraintViolations()) {

           report.addConstraintViolation(new RestConstraintViolation(

                   cv.getPropertyPath().toString(),

                    cv.getMessage(),

                    cv.getInvalidValue() ==null ? "null" : cv.getInvalidValue().toString()));

       }

       // 采用json输出代替xml输出

       returnResponse.status(Response.Status.INTERNAL_SERVER_ERROR).entity(report).type(ContentType.APPLICATION_JSON_UTF_8).build();

    }

}

Dubbox中时间参数的反序列成POJO对象的属性字段失败

在Dubbox开发过程中,如果需要将一个时间格式字符串反序列化成一个Date对象,会出现反序列失败的情况,查看报错信息,为Jboss的resteasy框架的序列化失败,而dubbox的接送序列化正是采用的这个序列化框架。所以我们需要采用注解@Deserializer对时间字段的反序列化进行指定,其反序列化类的具体如下所示:

public class CustomDateDeserialize extends JsonDeserializer<Date>{

private SimpleDateFormate sdf = new SimpleDateFormate("yyyy-MM-dd HH:mm:ss");

public Date deserialize(JsonParser jsonparser, DeserializationContext deserializationContext )  throws IOException, JsonProcessingException{

Date date = null;

try{

date = sdf.parse(jsonparser.getText());

}catch(Exception e){

e.printStackTrace();

}

return date;

}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值