Given the following POJOs:
public class BaseEntity {
public Long id;
// ctor, getter & setter
}
public class Widget extends BaseEntity {
public String fizz;
public Boolean isBuzz;
// ctor, getters & setters
}
I have the following client API for CRUDding Widget
instances against a remote REST service:
public class WidgetServiceClient {
public void createWidget(Widget w) {
// RESTful call: POST localhost/widgets
}
public Widget getWidgetById(Long id) {
// RESTful call: GET localhost/widgets/{id}
}
}
And the following RESTful service endpoints exposed:
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.
}
}
Let's pretend I've already figure out the "magic" of serializing/deserializing Widget
instances to/from JSON.
This design is great, except when there is a server-side Exception
that I want to communicate back to the client, RESTfully.
My first inclination was to modify BaseEntity
to have a Throwable
that could be used to communicate server-side errors back to the client-side:
public class BaseEntity {
public Long id;
public Throwable error;
// ctor, getters & setters
}
So then:
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;
}
}
But this feels kludgy/hacky, and I'm wondering if the other denizens of Javaland have already figured out a better approach/strategy to this problem. I happen to be using Jersey & Jackson for REST/serialization, but I'm thinking the solution should probably be framework-agnostic.
It also doesn't help when the service returns NULLs, which can happen.
So I ask: How can I pass Widget
instances back and forth between client and server, RESTfully, but still allow the server to return NULLs and Exceptions
/Throwables
?