js功能模块的错误隔离机制 - dongyuwei/blog GitHub Wiki

传统上,在不同<script></script>内执行的js,有异常错误时,不会互相影响. 但如果把多个<script></script>内js合并到一个<script></script>内,则前面的js模块出错时,会中止执行,导致异常点后面的功能模块完全失效.

解决办法很简单: 把不同功能模块封装到try catch中执行. 不要怕由此带来的性能损耗, 与性能相比,模块错误隔离带来的整体功能稳定性更加重要.

<!DOCTYPE html>
<html>
    <head>
        <title>
            js sandbox
        </title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    </head>
    <body>
        <script>
            alert('module 1');
        </script>

        <script>
            alert('module 2');
            throw 'some error in module 2 !';
        </script>

        <script>
            alert('module 3');
        </script>

        <script>
            alert('module 11');

            alert('module 22');
            throw 'some error in module 22 !';

            alert('module 33');//not executed
        </script>

        <script>
            function sandbox(func){
                try{
                   func.call(); 
                }catch(err){
                    if(window.console && window.console.error){
                        window.console.error(err);
                    }
                }
            };

            alert('sandbox module 1');

            sandbox(function(){
                alert('sandbox module 2');
                throw 'some error in sandbox module 2 !';
            });
            
            alert('sandbox module 3');//not executed
        </script>
    </body>
</html>
⚠️ **GitHub.com Fallback** ⚠️