QUESTION
1) How to handle errors in client-server application when using REST services? Could somebody help me with example code what is the best way to handle error messages in code below. How to catch exceptions in client side and/or server side in case of create-service for example?
2) How to forward user to different page in case of error and in case of success?
CLIENT
$('#btnSignup').click(function(){
var user = {"id": 10, "firstName": $('#firstName').val(), "lastName": $('#lastName').val(), "age": 69, "freeText": "55555", "weight": 55};
$.ajax({
type: "POST",
contentType: "application/json",
url: "http://localhost:8080/test/webresources/entity.user/",
dataType: "json",
data: JSON.stringify(user),
success: function(response) {
$('#myModal').modal('hide');
},
error: function(data) {
alert('addUser error: ');
}
});
});
REST SERVICE
@Stateless
@Path("entity.user")
public class UsersFacadeREST extends AbstractFacade<Users> {
@PersistenceContext(unitName = "testPU")
private EntityManager em;
public UsersFacadeREST() {
super(Users.class);
}
@POST
@Override
@Consumes({"application/xml", "application/json"})
public void create(Users entity) {
super.create(entity);
}
Just my 2 cents Well you can define a Result Object , which you can return after every rest call
IN the bean
You can later parse the response in HTML using jquery and handle the flow based on the 'status'
1) Create your own RESTException at server side.
2) Whenever you are responding with that exception; add that exception message in HTTP header.
3) In HTTP protocol use errorCode && errorMessage available in the header for your Exceptions at server side and decode it at client side to show meaningful data about that exception at client side.
Below is an example in C# client code to sending the request to Server; this has error handling mechanism.
Spring MVC REST Exception Handling part-1
Spring MVC REST Exception Handling part-2