我正在使用Java REST API来注册用户。我正在尝试检查发送给POST的用户是否具有所有有效的字段,以便可以将其保存到数据库,但是如果其中一个字段的类型无效,我将找不到处理错误的方法。
我的模型User.java
public class User{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@Column
private String description;
@Column
private String date_joined;
@Column
private double age;
//setters and getters
}
用户资源方法:
@POST
@Consumes("application/json")
@Produces("application/json")
public Response postUser(User User)
{
//validate User fields and save to db
// if valid return following, else send Bad Request
return Response.status(Response.Status.CREATED).entity(User).build();
}
我正在使用ajax通过以下方式发送数据:
{
"date_joined":"27/12/19",
"description":"Currently looking for job",
"age":30
}
在此示例中效果很好,但我想验证发送的数据是否为无效类型,例如:
{
"date_joined":"27/12/19",
"description":"Currently looking for job",
"age": "thirty"
}
这会出现以下错误
org.codehaus.jackson.map.JsonMappingException: Can not construct instance of double from String value 'thirty': not a valid Double value
有没有办法捕捉这些错误?因此,以后我可以例如向用户发送一条消息,告知他们发送了无效数据
答案 0 :(得分:0)
解决方案是捕获异常并在出现JsonMappingException的情况下返回错误消息吗?
try {
return Response.status(Response.Status.CREATED).entity(User).build();
} catch (JsonMappingException e) {
// Return a 4xx statuscode to indicate a client error and some json containing e.getMessage()
}
请告诉我这是否有用!谢谢!
:)
答案 1 :(得分:0)
是的。有一种方法。我们可以编写自己的自定义解串器。
我为电子邮件验证编写了反序列化器/验证器。
import org.apache.commons.lang.StringUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
public class EmailValidator2 extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException, JsonProcessingException {
System.out.println("Intercepting deserlization to validate email....");
ObjectCodec objectCodec = jsonParser.getCodec();
JsonNode jsonNode = objectCodec.readTree(jsonParser);
String value = jsonNode.asText();
if (StringUtils.isNotBlank(value) && (!org.apache.commons.validator.routines.EmailValidator.getInstance().isValid(value))) {
throw new RuntimeException("Email address is invalid");
}
return jsonNode.asText();
}
}
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.module.SimpleModule;
@Service
public class CustomSerializerAndDeserializerRegistry extends SimpleModule {
public CustomSerializerAndDeserializerRegistry() {
this.addDeserializer(String.class, new EmailValidator2());
}
}
public class User{
private String email;
public String getEmail() {
return email;
}
@JsonDeserialize(using = EmailValidator2.class)
@ExceptionHandler
public void setEmail(String email) {
this.email = email;
}
}
如果需要,我可以提供更多帮助。