Raise jQuery ajax callback error from inside servlet

Inside my ajax call, if an error is received, I have a warning:

$.ajax({ url: "myUrl", type: 'POST', dataType : "text", data : ({ json : myJson }), success : function(data) { alert('success'); }, error : function() { alert ('error'); } 

Inside java, you can send back to cause an error callback in jquery if an exception is thrown. So something like:

  try { PrintWriter out = resourceResponse.getWriter(); out.println("success"); out.close(); } catch (Exception e) { PrintWriter out = resourceResponse.getWriter(); out.println("error"); out.close(); } 

ie, instead of printing an "error" in the response, the "error" callback is called inside jQuery code.

+6
source share
3 answers

You must set the http status code for something other than 200 to call the error callback in jQuery Ajax. You can set the static error 500 (which is for Internal Server Error) as

 catch (Exception e) { resourceResponse.setProperty(resourceResponse.HTTP_STATUS_CODE, "500"); PrintWriter out = resourceResponse.getWriter(); out.println("error"); out.close(); } 

in your catch .

+4
source

You have two options:

  • Handle every error in the servlet and wrap the error / success information in a JSON response as indicated by Cranio
  • Use HttpServletResponse to set the status code to http 500 (or another error code) and then just handle the error callback in jQuery script
+2
source

Use the AJAX page to return a JSON object with two values

  • factual data
  • error code

So you can handle the error logic on the AJAX page. These solutions take into account user errors on your AJAX page; errors in AJAX calls can be handled by your existing code.

+1
source

Source: https://habr.com/ru/post/918359/


All Articles