0

If the user doesn't input a correct string it will fail the try. it's fine

My only problem is that I want to send the exception to the error function in the ajax. ATM is sending it to the success.

How do I trigger some sort of error so it sends to the error function in ajax?

public static String call(String input) {

    try {
        //doesn't matter. it will fail this try

        }
    } catch (Exception e) {
        return e.getMessage(); // I want to send this to the error function in ajax
    }
    return "Good job";
}

AJAX

$.ajax({
      url: '/call',
      type: 'get',
      data: {input: input},
      success: function (resultString) {
          //it sends to here instead of error
      },
      error: function () {
          // i want to see it here
      }
  })
3
  • Isn't the error function triggered by sending back a response status code that is not in the 2xx range? Commented Apr 9, 2018 at 11:30
  • I have no idea. Commented Apr 9, 2018 at 11:30
  • 1
    unrelated: "Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead." - api.jquery.com/jQuery.ajax Commented Apr 9, 2018 at 13:05

3 Answers 3

1

This question is use case dependent, as the correct answer depends on the type of error, business rules and other factors like information exposure.. but to try sending you in the correct direction, you will need to send an HTTP error code, probably a 400 as in https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400

This is an example of a how a servlet can do it (this is also case dependent as the method to use depends on you back end tech):

catch ( MalformedFileUriException e ) {
            response.setStatus( HttpServletResponse.SC_BAD_REQUEST );
            log.warn( "...", e );
        }
        catch ( UnsupportedLocaleException e ) {
            response.setStatus( HttpServletResponse.SC_BAD_REQUEST );
            log.warn( "...", e );
        }
        catch ( Exception e ) {
            response.setStatus( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
            log.error( "...", e );
        }
Sign up to request clarification or add additional context in comments.

3 Comments

What about the e.getMessage(); ?? How do I send it?
Assuming you are using just a simple servlet... docs.oracle.com/javaee/7/api/javax/servlet/http/…
Remember to accept an answer, if you found one. It is important, so people don't keep trying to solve an answered issue. welcome to SO, btw.
0
public static String call(String input) {

    try {
        //doesn't matter. it will fail this try

        }
    } catch (Exception e) {
        echo json_encode(array("status"=>false,"msg"=>e.getMessage())); // I want to send this to the error function in ajax
    }
    echo json_encode(array("status"=>true,"msg"=>"Good job"));
}

JS

$.ajax({
      url: '/call',
      type: 'get',
      data: {input: input},
      success: function (resultString) {
          var d = $.parseJSON(resultString);
          if(d.status){
          //do stuff
          }else{
          alert(d.msg);//Your alert message
          }
      }
  })

AJAX doesn't catch the error thrown by server in error function. You need to do it manually to let AJAX know if it was a success or an error. You need to use json_encode and set status true or false.

Check in your AJAX if status is false it means the error was thrown from the server.

PS - I don't know the json_encode syntax in JAVA so I have used the syntax of PHP. Please replace it. But you will get the idea from this.

3 Comments

surely there's a cleaner and simplier way to do it?
As far as I know AJAX error function won't catch the error from your catch function. You need to what I have suggested. If you can find a better way please post it here so it can help someone, but I don't think there is a cleaner way than this. :) @user9565299
It won't give you the exception, but if you return an HTTP error response, you will trigger the error function(s), see: api.jquery.com/jQuery.ajax
0

The ajax success or error gets executed when the AJAX call completes successfully or fails respectively. So basically it does not care what result you are returning from backend. if your backend fails to return any data, only then the AJAX will run into an ERROR block. so if you want to distinguish between your try block returning data and error block returning data you have to apply some logic in your success part of AJAX. So my approach would be to send the data as a list of text and value rather than a string. you can set the [text] part as "OK" when your backend return data from a try block or else you can set the [text] block as "Error" in case of catch block returning. And the [Value] of list would be the desired values. So conclusion use list<> in place of string as a return type, and set the [Text] and [Value] field as required.

3 Comments

" if your backend fails to return any data, only then the AJAX will run into an ERROR block" - wrong.
@Fildor the statement is in context to what the question asks for. I should rather write that "if the backend returns data to the ajax call i.e if the request is successful, then only the success/complete parameters will get executed and the error block will not get called. My understanding may be wrong, if so please do let me know.. i would be happy to learn.
That is correct. My point was: if the endpoint responds with for example 404 Status, the error callback will fire. And I interpret answering with an error status as "return data" - just to clarify why I find the quoted statement to be incorrect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.