什么是异常?这意味着用户在使用该应用程序时无法获得预期的结果。不同的异常有不同的后果,从引起用户的不满,到导致产品无法使用,导致用户失去对产品的认可。为什么我们需要处理异常来提升用户体验?远程定位问题无法重现,尤其是在移动端。各种原因可能是系统版本、型号等,前端的异常和异常有哪些?javascript异常(语法错误、代码错误)往往是静态的资源加载异常(img、js、css)不是语法和异步错误。1.同步操作错误try{kill;}catch(err){console.error('try:',err);}结果:try:ReferenceError:killisnotdefined2.无法捕获语法错误try{letname='1;}catch(err){console.error('try:',err);}结果:未终止的字符串常量编译器可以防止运行时语法错误。3.无法捕获异步错误result:UncaughtTypeError:Cannotreadproperty'map'ofundefinedwindow.onerror当发生JavaScript运行时错误(包括语法错误)时,window会触发ErrorEvent接口的error事件,执行window.onerror()函数,如果返回true,阻止执行默认事件处理程序。1.同步操作错误/***@param{String}message错误信息*@param{String}源错误文件*@param{Number}lineno行号*@param{Number}colno列号*@param{Object}error错误对象*/window.onerror=(message,source,lineno,colno,error)=>{console.error('Catchexception:',message,source,lineno,colno,error);returntrue;};kill;Result:Catchexception:UncaughtReferenceError:killisnotdefined2,cannotcatchsyntaxerror/***@param{String}message错误信息*@param{String}源错误文件*@param{Number}lineno行号*@param{Number}colno列号*@param{Object}error错误对象*/window.onerror=(message,source,lineno,colno,error)=>{console.error('Catchexception:',消息,来源,lineno,colno,错误);返回真;};让名字='1;结果:未终止的字符串常量编译器能够防止运行时语法错误。3.异步错误/***@param{String}message错误信息*@param{String}源错误文件*@param{Number}lineno行号*@param{Number}colno列号*@param{Object}错误错误对象*/window.onerror=(message,source,lineno,colno,error)=>{console.error('Catchexception:',message,source,lineno,colno,error);returntrue;};setTimeout(()=>{undefined.map(v=>v);},1000);结果:捕获异常:UncaughtTypeError:Cannotreadproperty'map'ofundefined\`window.addEventListener('error')作为资源(如或window.addEventListener('error',(err)=>{console.error('Catchexception:',err);},true);
