鑑於以下的POJOs:REST錯誤響應和客戶端服務器POJO系列化
public class BaseEntity {
public Long id;
// ctor, getter & setter
}
public class Widget extends BaseEntity {
public String fizz;
public Boolean isBuzz;
// ctor, getters & setters
}
我有CRUDding Widget
情況下,對遠程REST服務以下客戶端API:
public class WidgetServiceClient {
public void createWidget(Widget w) {
// RESTful call: POST localhost/widgets
}
public Widget getWidgetById(Long id) {
// RESTful call: GET localhost/widgets/{id}
}
}
而下面暴露的RESTful服務端點:
public class WidgetService {
// Web server passes POST localhost/widgets/ calls to this method.
public Widget createWidget(Widget w) {
// Create the 'w' widget in the DB and return it with its DB-generated ID.
}
// Web server passes GET localhost/widgets/{id} calls to this method.
public Widget getWidgetById(Long id) {
// Ask the DB for the Widget with the passed-in 'id'. If it exist return it.
// Otherwise return NULL.
}
}
讓我們假裝我'我已經找出了向/從JSON序列化/反序列化實例的「魔術」。
這個設計很好,,除了,當有一個服務器端Exception
,我想通過RESTfully回傳到客戶端。
我的第一個傾向是修改BaseEntity
有一個Throwable
可用於通訊服務器端錯誤返回給客戶端:
public class BaseEntity {
public Long id;
public Throwable error;
// ctor, getters & setters
}
那麼接下來:
public class WidgetService {
// Web server passes POST localhost/widgets/ calls to this method.
public Widget createWidget(Widget w) {
try {
// Create the 'w' widget in the DB and return it with its DB-generated ID.
} catch(Throwable t) {
w.setError(t);
}
return w;
}
// Web server passes GET localhost/widgets/{id} calls to this method.
public Widget getWidgetById(Long id) {
Widget w = new Widget();
try {
// Ask the DB for the Widget with the passed-in 'id'. If it exist return it.
// Otherwise return NULL.
} catch(Throwable t) {
w.setError(t);
}
return w;
}
}
但這感覺很糟糕/哈克,我想知道其他的Javaland居民是否已經找到了解決這個問題的更好方法/策略。我發生將使用澤西&傑克遜REST /序列化,但我認爲該解決方案應該可能是框架無關。
當服務返回NULL時它也沒有幫助,這可能發生。
於是我問:如何傳遞Widget
實例來回客戶端和服務器之間的REST風格,但仍允許服務器返回空值和Exceptions
/Throwables
?
謝謝@starver(+1) - 404響應將JSON仍包含「實體」('e.getMessage()')? – smeeb 2014-10-28 10:06:34
是的。客戶端的Response對象將包含狀態碼和實體。當客戶端沒有收到成功代碼時,他們可以通過Response.readEntity(String.class)來讀取你的錯誤信息。通常,錯誤響應對象是字符串,鍵值對的映射或定製的豐富錯誤對象,具體取決於API的健壯性。無論您選擇哪種方式,錯誤響應實體都應該在整個API中保持一致。 – 2014-10-28 19:58:47