简体   繁体   中英

How to trigger a function in Javascript

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
      }
  })

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 );
        }
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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM