2

I'm trying to detect when a console error occurs. I've looked here and have seen 2 suggestions

window.onerror and try catch

The following demonstrates an issue where this is not "caught" (by caught, as per the code below, I'd expect to see an alert and I do not).

window.onerror = function(error) {
    alert("window error..." + error );
}

    const arr = [];

try{
    arr.push({
        'firstValue':'Me 'And' You',
        'otherValue':5
    });
}catch(err){
    alert("Error..." + err);
}

The part causing the issue is

'firstValue':'Me 'And' You',

The reason for this is how this line of code is generated and I suspect the real fix is to correct this (using MVC.NET Razor)

'firstValue': '@Model.MyStringWithNoFormattingOrChecking'

Where the value of MyStringWithNoFormattingOrChecking is Me 'And' You

However, my question is about why the onerror or try catch didn't work. Or what I could have done to have caught this using javascript (I don't actually show an alert, I log via Ajax)

7
  • 3
    Syntax errors are not catched at runtime, since a code having a syntax error is never executed. Commented Jan 23, 2018 at 11:50
  • 2
    I don't think you can catch plain syntax errors like that with javascript. The parser will stop after the 'Me ' Commented Jan 23, 2018 at 11:50
  • @baao, if I'm using the wrong tool/tech, then that is fine. What could I use instead of JavaScript then? Commented Jan 23, 2018 at 11:51
  • 1
    You need to properly escape the ' within the string. I've never used MVC.NET, so I can't say how to fix the creation of the string - but I'd look there first instead of on the js part Commented Jan 23, 2018 at 11:52
  • 1
    This is indeed an escaping issue within .NET rather than a JavaScript error handling issue. This article is an excellent summary of the issue at hand. Commented Jan 23, 2018 at 11:54

1 Answer 1

2

Try putting the onerror code in its own script tag, which runs earlier than this syntax error.

This code does what you want

<head>
    <script type="text/javascript">

window.onerror = function(error) {
    alert("window error..." + error );
}
    </script>


    <script type="text/javascript">
const arr = [];

try{
    arr.push({
        'firstValue':'Me 'And' You',
        'otherValue':5
    });
}catch(err){
    alert("Error..." + err);
}
    </script>

</head>

[tested in Firefox, Chome and Edge]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.