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
Class Result{
private String statusCode;
private String statusDescription;
}
IN the bean
@POST
@Override
@Consumes({"application/xml", "application/json"})
@Produces({ "application/json"})
public Result create(Users entity) {
Result result = new Result();
try{
super.create(entity);
result.setStatus("200");
result.setStatusDescriptions("Success");
}catch(Exception) {
result.setStatus("500");
result.setStatusDescriptions("Fail");
}
return result; // Return this as Json
}
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.
HTTP Status: 500 - Internal Server Error
Response Headers:
Date=Wed, 09 Jan 2013 13:41:15 GMT
Server=Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8e-fips-rhel5 mod_jk/1.2.28
errorCode=4567
errorMessage=invalid conference passcode
Accept-Charset=big5, big5-hkscs, compound_text, euc-jp, euc-kr, gb18030, gb2312, gbk, ibm-thai, ibm00858, ibm01140, ibm01141, ibm01142, ibm01143, ibm01144, ibm01145, ibm01146, ibm874, x-ibm875, x-ibm921, x-ibm922, x-ibm930, x-ibm933, x-ibm935, x-ibm937, x-ibm939, x- x-windows-50221, x-windows-874, x-windows-949, x-windows-950, x-windows-iso2022jp
Content-Length=6406
Connection=close
Content-Type=application/xml
Response Body:
4567: invalid conference passcode
com.xxx.exceptions.InvalidPasscodeException invalid conference passcode
at com.xxx.dao.impl.context.multipleconfs.ResLessConfDao.validatePasscode(ResLessConfDao.java:754)
at
Below is an example in C# client code to sending the request to Server; this has error handling mechanism.
public static bool sendRequest(string requestURL, HTTPRequestMethod requestMethod,
NetworkCredential m_netCred, String xml, ErrorResponse m_objErrorResponse)
{
try
{
HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;
request.PreAuthenticate = true;
request.Credentials = m_netCred;
request.Method = requestMethod.ToString();
request.AllowAutoRedirect = false;
request.ReadWriteTimeout = 100000;
request.ContentLength = xml.Length;
request.ContentType = "application/xml; encoding='utf-8'";
Debug.WriteLine("XML: {0}", xml);
StreamWriter postStream = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
postStream.Write(xml);
postStream.Close();
WebResponse response = request.GetResponse();
response.Close();
}
catch (WebException webex)
{
var response = webex.Response as HttpWebResponse;
int errCode = 0;
if (response != null)
{
errCode = (int)response.StatusCode;
Debug.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
if ((int)response.StatusCode != 500) //Other errors
{
m_objErrorResponse.UpdateErrorResponse(errCode.ToString(), response.StatusCode.ToString(), "");
}
else
{
m_objErrorResponse.UpdateErrorResponse(errCode.ToString(), response.StatusCode.ToString(),
response.Headers.ToString().Split('\n')[1].Substring(14).Trim());
}
}
return false;
}
return true;
}
}
Spring MVC REST Exception Handling part-1
Spring MVC REST Exception Handling part-2