您可以返回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中表現不佳。創建我自己的簡單版本變得更簡單。