我正在使用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,因此程序存在错误。但是当它试图读取错误的内容时,它会在尝试阅读NullPointerException
时抛出exception.getErrorMessage()
,因为当然没有错误。
为什么将{}
视为有效的ProcessingException
对象?
答案 0 :(得分:2)
杰克逊没有进行bean验证。但是你可以做的是将构造函数声明为JsonCreator,它将用于实例化新对象并检查/抛出异常,如果该字段为null:
class ProcessingException {
private String errorMessage;
@JsonCreator
public ProcessingException(@JsonProperty("errorMessage") String errorMessage) {
if (errorMessage == null) {
throw new IllegalArgumentException("'errorMessage' can't be null");
}
this.errorMessage = errorMessage;
}
// getters, setters and other methods
}