goGud goGud - 3 months ago 21
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

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 {

  public  enum UserCodes { SUCCESS, DATA_ALREADY_EXIST, DATA_WRONG_FORMAT };

 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)

  @GET
  @Path("/insertRecord") 
  @Produces(MediaType.APPLICATION_XML))
  public UserMessage someInsertMethod(@QueryParam("id") int id){
  UserMessage uMsg = new UserMessage();
  try{
//try insert here

 }catch(SqlException sqle){

  switch (sqle.getErrorCode()){
  case num1:  //replace num1 with the actual error code
    uMsg.setUserCode(UserMessage.UserCodes.DATA_ALREADY_EXIST);
    uMsg.setUserMsg(" Key already exists");
    break;
  case num2:
  uMsg.setUserCode(UserMessage.UserCodes.DATA_WRONG_FORMAT);
    uMsg.setUserMsg(" Data wrong format");
    break;
  }
  }
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());   

            try{
                UserMessage msg =(UserMessage) target.path("rest").path("insertRecord").request()
                .accept(MediaType.APPLICATION_XML).get(UserMessage.class);

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


            }catch(Exception e){
                System.out.println(e);
                return;
            }

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