java空JSON响应不会触发Jackson中的错误
我正在使用Jackson解释来自我正在编写的API的JSON响应。作为整个API的标准,我希望通过以下方式将错误从API抛出到程序:
{"errorMessage":"No such username."}
因此,我希望我的响应处理器首先检查响应是否只是一个errorMessage键,如果是,则处理错误,如果不是,则将其解释为它期望从该命令得到的任何响应
这是我的代码:
public class ProcessingException extends Exception {
private String errorMessage;
public ProcessingException(){}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
然后,在我的响应处理程序中:
@Override
public void useResponse(InputStream in) throws IOException, ProcessingException {
// turn response into a string
java.util.Scanner s = new java.util.Scanner(in).useDelimiter("\\A");
String response = s.hasNext() ? s.next() : "";
ProcessingException exception;
try {
// Attempt to interpret as an exception
exception = mapper.readValue(response, ProcessingException.class);
}
catch(IOException e) {
// Otherwise interpret it as expected. responseType() is an abstract TypeReference
// which is filled in by subclasses. useResponse() is also abstract. Each subclass
// represents a different kind of request.
Object responseObj = mapper.readValue(response, responseType());
useResponse(responseObj);
return;
}
// I needed this out of the try/catch clause because listener.errorResponse might
// actually choose to throw the passed exception to be dealt with by a higher
// authority.
if (listener!=null) listener.errorResponse(exception);
}
这很好地工作,除了在一种情况下-有一些请求实际上不需要任何响应,因此它们返回{}
。出于某种原因,此响应完全通过exception = mapper.readValue(response, ProcessingException.class);
行运行,而不会触发IOException,因此程序会判断是否存在错误。但是当它尝试读取错误时,它在尝试读取exception.getErrorMessage()
时抛出一个NullPointerException
,因为当然没有错误
为什么它将{}
视为有效的ProcessingException
对象
# 1 楼答案
Jackson没有bean验证。但您可以将构造函数声明为JsonCreator,用于实例化新对象,并在该字段为空时检查/抛出异常: