您可以返回HTTP 500或您选择的代码(来自org.springframework.http.HttpStatus枚举),并使用自定义错误来模拟JSON响应内的SOAP错误。
例如:
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(YourTargetException.class)
@ResponseBody
Fault caughtYourTargetException(HttpServletRequest req, Exception ex) {
String code = ex.getClass().getName();
String reason = "Caught YourTargetException."
return new Fault(code, reason);
}
Fault类可以是这个样子(通过http://www.w3.org/TR/soap12-part1/#soapfault启发):
/**
* A Fault is an object that can be serialized as JSON when expected errors occur.
*/
public class Fault {
@JsonProperty("faultCode")
private final String code;
@JsonProperty("faultReason")
private final String reason;
@JsonProperty("faultDetails")
private final List<String> details = new ArrayList<>();
public Fault(String code, String reason) {
this.code = code;
this.reason = reason;
}
public Fault(String code, String reason, String... detailEntries) {
this.code = code;
this.reason = reason;
details.addAll(Arrays.asList(detailEntries));
}
public String getCode() {
return code;
}
public String getReason() {
return reason;
}
/**
* Zero or more details may be associated with the fault. It carries
* additional information relative to the fault. For example, the Detail
* element information item might contain information about a message
* not containing the proper credentials, a timeout, etc.
* @return Zero or more detail entries.
*/
public Iterable<String> getDetails() {
return details;
}
@Override
public String toString() {
return String.format("Fault %s occurred. The reason is %s.", getCode(),
getReason());
}
}
你可以使用Java框架现有SOAPFaults之一,但我有发现它们在REST中表现不佳。创建我自己的简单版本变得更简单。