How to trigger the onError client side event

383 views Asked by At

I have a button with some SSJS code in the click eventhandler. It basically calls a Java method that says true or false. Therefor I'd like to trigger also the onComplete and the onError CSJS scripts: onComplete for success, onError for failure. Unfortunately I didn't figure out yet how to trigger the onError event - at least not in an elegant way. My first approach is to return a HTTP status code other than 200 (here 500). This triggers the onError but produces an ugly error message in the browser console.

So are there any other options to control the outcome of the SSJS to call either the onComplete or the onError script?

UPDATE

Meanwhile I found a workaround but I'm still interested in a solution for my question.

My workaround was not to use the onComplete/onError scripts but to call my both success/fail scripts directly in my SSJS via

view.postscript("success()");

and

view.postscript("fail()");

That's a cleaner approach I think.

1

There are 1 answers

0
Sven Hasselbach On BEST ANSWER

You could send back your own status code in the SSJS or Java event:

<xp:this.action><![CDATA[#{javascript:facesContext.getExternalContext().getResponse().setStatus(999);}]]></xp:this.action>

To prevent the console logging, you can disable them with the failOk parameter of Dojo's xhr request (disables the console logging for all requests):

if( !dojo._xhr )
    dojo._xhr = dojo.xhr;

dojo.xhr = function(){        
    try{
        var args = arguments[1];   
        args["failOk"] = true;
        arguments[1] = args;
    }catch(e){}

    dojo._xhr( arguments[0], arguments[1], arguments[2] );
}

Now you can add an error handler method to your event:

<xp:this.onError><![CDATA[errorHandler(arguments[0], arguments[1])]]></xp:this.onError>

In the method, you can check the status code from your event and do what you want if the code matches:

<script>
    function errorHandler(err, xhr){
        if( err.status == 999 ){
            // whatever
        }
    }
</script>