goGud goGud - 1 year ago 90
reST (reStructuredText) Question

How to return database error from restful service?

I am writing both server and client side. If request is successful or have error like HTTP 404, 400, 405 etc... I can handle it without any problem. However, I dont know what is the best way to handle errors from database side. Like;

ERROR: duplicate key value violates unique constraint "UserInfo_image_id_key"
SQL state: 23505
Detail: Key (image_id)=(123123) already exists.

If there is update on db I can check it like;

int result = ps.executeUpdate();
if (result > 0) {
System.out.println("Successfully updated");
return true;
} else {
System.out.println("DB not updated!");
return false;

Could you please help me how I can handle such error case on
else loop

Answer Source

In order to return a user message back to the client, you First need to create a simple Java class (POJO) that will contain the message.

Your POJO might look like

 import java.io.Serializable;
 import javax.xml.bind.annotation.XmlRootElement;

 @XmlRootElement(name = "userMsg")
 public class UserMessage implements Serializable {


 private enum userCode ;
 private String userMsg ;

 public UserMessage(){
 userCode = UserCodes.SUCCESS; //DEFAULT
 userMsg =  "Request successful";

 public UserCodes getUserCode(){
return userCode;
public void setUserCode(UserCodes code){
 userCode = code;
public String getUserMsg(){
return userMsg;
 public void setUserMsg(String msg){
 userMsg = msg;

Your server side code (Jersey in my case)

  public UserMessage someInsertMethod(@QueryParam("id") int id){
  UserMessage uMsg = new UserMessage();
//try insert here

 }catch(SqlException sqle){

  switch (sqle.getErrorCode()){
  case num1:  //replace num1 with the actual error code
    uMsg.setUserMsg(" Key already exists");
  case num2:
    uMsg.setUserMsg(" Data wrong format");
return uMsg;

Note that Jersey is converting a UserMessage into an XML (serialization). This could of course, be JSON.

The client code (again Jersey assumed)

           ClientConfig config = new ClientConfig();

            Client client = ClientBuilder.newClient();

            WebTarget target = client.target(UriBuilder.fromUri("http://localhost:8088/JerseyRest").build());   

                UserMessage msg =(UserMessage) target.path("rest").path("insertRecord").request()

               if(msg.getUserCode() != UserMessage.UserCodes.SUCCESS)
                   System.out.println("Msg: " + msg.getUserMsg());

            }catch(Exception e){

In your client code just check that msg.getUserCode() != UserMessage.UserCodes.SUCCESS and then display the error message.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download