Get responsible for error

Asked

Viewed 58 times

1

There is the possibility of knowing which element in the HTML is responsible for the error causing action in Javascript?

code:

<button onclick="a(this);">GO!</button>
<script>
window.onerror = function(message, source, lineno, colno, error) {
  console.log(error.stack); // event.target = window
}
</script>

Exit:

Referenceerror: a is not defined

At Htmlbuttonelement.onclick (onerror.html:1)

In this reference "Htmlbuttonelement.onclick" says that it is a button and that it was in the onclick event, but at the same time it says nothing, I am not able to select this element somehow, or will be that way, using the stack is not possible? Would have another way to "arrive" in this element?

var domID = "HTMLButtonElement".id;
addObjLog(document.querySelector(domID)); //exemplo de uso
  • ReferenceError: a is not defined - Here is saying that the function a is not defined, that is, it does not exist in the context you are calling it.

  • @Pedrocamarajunior is not quite that, the error is purposeful, to trigger the event of onerror, the idea would be to know that it was the button that made the error through this event

  • Ah, okay. I get it. =/

1 answer

0

One of the ways to do this is to pick up the exception and re-launch it with an element identifier that caused the error.

<button id="btn" onclick="try{a(this);}catch(err){throw new Error(event.target.id)}">
    GO!
</button>
<script>
    window.onerror = function(message, source, lineno, colno, error) {
      console.log(error.message);
    }
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.