0

Just like we catch display error with apex:pageMessages tag, is there any way to catch visualforce errors?

Sample error:

Visualforce Error : Division field undefined

I get the above error when the denominator is zero. I used javascript to handle this.

But I was wondering, if there's a general way of catching all visualforce error and displaying a friendlier message than a Visualforce Error.

2

This type of requirement is a bit non traditional as users don't like to see such errors.

Maybe helpful for developers, but they can always see these in browsers developer tool's console.

Can be done, combining example from following-

  1. Manage (and re-use) apex:pageMessages from Javascript (SFSE)
  2. How to catch all javascript warnings and errors to an output div? (Stackoverflow)

Desired output as example has an error on page load:

enter image description here


Page:

<apex:page controller="LogException">
    <script>
        // method to handle generic page error
        window.onerror = function(errorMsg, url, lineNumber){
            showMessage('ERROR', "Error in " + url + " at " + 
                lineNumber + ":\n" + errorMsg);
        }

        // onload handler
        window.onload = function() { 
            // would give an exception on load as variable hi is not defined
            alert(hi);
        }

    </script>

    <apex:form>
        <apex:pageMessages id="jserror"/>

        <apex:actionFunction name="showMessage" 
            action="{!showMessage}" rerender="jserror">
            <apex:param name="errorLevel" assignTo="{!errorLevel}" 
                value="" />
            <apex:param name="messageName" assignTo="{!messageName}" 
                value="" />
        </apex:actionFunction>
    </apex:form>

</apex:page>

Controller:

public class LogException {

    public String errorLevel { get; set; }
    public String messageName { get; set; }

    public void showMessage() {
        if(errorLevel == 'ERROR') {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Warning, 
                messageName));
        }
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.