Pergunta

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);
}
Foi útil?

Solução 2

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

Outras dicas

This works fine:

try {
    decodeURI('%C4%97%')
} catch (ex) {
    alert("ERROR DECODING URI");
}

DEMO: http://jsfiddle.net/P6EBN/

EDIT:

From the looks of your error message, you're trying to set a textarea's value with jQuery.

Try something like this:

var newVal = "";
var toDecode = jQuery('input#encode-url-input').val();
try {
    newVal = decodeURI(toDecode);
} catch (ex) {
    // alert("ERROR DECODING URI");
}
jQuery('textarea#encode-url-result').val(newVal);

Just trying to split it up so you can target specifically the decoding.

Also, the use of a tagName in front of an id selector is unnecessary. Just use these selectors:

jQuery("#encode-url-input")
// and
jQuery("#encode-url-result")
try {
    var x = decodeURIComponent('%C4%97%');
} catch (ex) {
    console.log("ERROR DECODING URI: " + ex.message);
}
try
{
    var x = decodeURI('%C4%97%');
}
catch(e)
{
    alert(e);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top