javascriptdecodeuricomponent

How to catch error when using decodeURI?


For example if use decodeURI('%C4%97%') it fires and error (yes, it is an error, specially for test):

URIError: malformed URI sequence ...('textarea#encode-url-result').val(decodeURI(jQuery('input#encode-url-input').va...

And even if i put it in try-catch it still fires fatally. Is there a way to catch it and show alert?

UPDATE:

Here is my code and i still get error in console

try{
    jQuery('a#encode-url-encode, a#encode-url-decode').click(function(){
        if(jQuery('input#encode-url-input').val().length == 0)
            showCustomAlert('<strong>Warning!</strong> Please enter value.');

        var result = null;

        if(jQuery(this).attr('id') == 'encode-url-encode')
            result = encodeURI(jQuery('input#encode-url-input').val());
        else if(jQuery(this).attr('id') == 'encode-url-decode')
            result = decodeURI(jQuery('input#encode-url-input').val());

        jQuery('textarea#encode-url-result').val(result);
    });
}
catch(e){
    alert(e);
}

Solution

  • Try-catch doesn't work if it wraps async callback passing.

    jQuery('a#encode-url-encode, a#encode-url-decode').click(function() {
        if (jQuery('input#encode-url-input').val().length == 0) showCustomAlert('<strong>Warning!</strong> Please enter value.');
        var result = null;
        try { //It needs to be here.
            if (jQuery(this).attr('id') == 'encode-url-encode') result = decodeURI(encodeURI(jQuery('input#encode-url-input').val()));
            else if (jQuery(this).attr('id') == 'encode-url-decode') result = decodeURI(decodeURI(jQuery('input#encode-url-input').val()));
        } catch (e) {
            //handle
        }
        jQuery('textarea#encode-url-result').val(result);
    });