how to catch a “Maximum call stack size exceeded” error?

前端 未结 4 1240
走了就别回头了
走了就别回头了 2021-01-14 17:58
  try {
     requestAnimationFrame(function re(){
       re();
     })}
  catch (e){
       console.log(e);
     }

I tried above code in console, i

4条回答
  •  花落未央
    2021-01-14 18:17

    Maximum call stack size exceeded errors can be caught just like any other errors:

    try {
      function recur() { recur(); };
      recur();
    } catch (ex) {
      console.log("caught " + ex);
    }

    What to do in this situation (call stack size exceeded) is not defined in the ECMAScript specification, but in practice, all browsers do throw catchable exceptions. However, lacking a spec different browsers have chosen to throw different types of exceptions: I've seen Error, RangeError and InternalError.

    The problem in your code is unrelated to that. The problem is that you're trying to catch exceptions that happen when you call requestAnimationFrame(). But your re() function doesn't run at that point, it runs during the next frame, as you requested. Inside of re(), you can wrap the recursive call to re() and catch the stack overflow exception there instead:

    requestAnimationFrame(function re(){
      try {
        re();
      } catch (ex) {
        console.log("caught " + ex);
      }
    });

提交回复
热议问题