【问题标题】:Rest service number validation休息服务号码验证
【发布时间】:2018-05-08 13:12:51
【问题描述】:

我在 Spring Boot 中有一项休息服务。我有一个post方法。在 post 方法中,我接受 json。这是工作。但是当客户端向我发送 userId 字段(短)的字符时,我会出现 json 解析错误。我可以在异常之前控制它吗?我想自定义错误信息但是异常信息太复杂了。

@RequestMapping(value = "/customers", method = RequestMethod.POST)
public ResponseEntity<?> insertCustomer(@Valid @RequestBody InsertParams 
params)
/*
*/}

public class InsertParams() {
private Short userId;
}

错误信息是: JSON解析错误:无法从字符串“a”反序列化java.lang.Short类型的值:不是有效的短值

【问题讨论】:

  • 您的 userId 字段的类型为 long,但您错误地说 String 无法转换为 Short?这没有多大意义。
  • 抱歉我的错误,我已经修复了
  • 请求负载是否包含作为char 的字母a 或十进制97(a 的ascii 代码)?根据您的 pojo 和您提出问题的方式,我认为请求有效负载应该是 {"userId":97}
  • 或者您是在问如何在收到包含无效内容的请求时控制错误消息/异常处理?在这种情况下,您可以考虑编写一个 ControllerAdvice 类来处理抛出的特定异常(JsonParseException ?)
  • 有效载荷包括一个字符,我得到这个错误。我可以在控制器建议中处理异常,但消息太长,我不知道如何拆分它

标签: java spring rest spring-boot service


【解决方案1】:

我是这样做的。

@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<ExceptionResponse> 
handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {

    String fieldName = "";

    String message = "";

    if (!(ex.getCause() instanceof JsonMappingException)) {
        return new ResponseEntity<ExceptionResponse>(HttpStatus.BAD_REQUEST);
    }

    JsonMappingException e = (JsonMappingException) ex.getCause();

    for (JsonMappingException.Reference reference : e.getPath()) {
        fieldName = reference.getFieldName();
    }

    if (fieldName.toLowerCase().contains("date"))
        message = fieldName + " format exception. Should be yyyy-MM-dd";
    else
        message = fieldName + " can not take characters.";

    ExceptionResponse er = new ExceptionResponse();
    er.setResult("Failure");
    er.setStatus(HttpStatus.BAD_REQUEST.value());
    er.setDescription(message);

    return new ResponseEntity<ExceptionResponse>(er, HttpStatus.BAD_REQUEST);

【讨论】:

    猜你喜欢
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 2012-07-27
    • 2021-10-03
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多