try...catch

2019-12-09  本文已影响0人  Bbang呀_

使用async await的时候,try包裹异步请求就可以了:

            let resp;
            try {
                resp = await API.geInfo(param) || {}; 
            } catch (error) {
                toast.info({
                    message: '网络异常,请检查网络'
                })
                return
            }

            if (resp.code === 0 && resp.body) {
               // 一些处理
               // ....
            } else {
            }
            

一般都是网络问题才会走到catch中。

若是包裹整个请求处理内容,如

           try {
               const resp = await API.geInfo(param) || {}; 
               if (resp.code === 0 && resp.body) {
               // 一些处理
               // ....
               } else {
               }
           } catch (error) {
               toast.info({
                   message: '网络异常,请检查网络'
               })
               return
           }

那么在对接口数据的处理过程的任何异常都会捕获,走到catch里,与我们的期望不符;同时发现的问题也不会被上报到sentry中。

因此推荐try..catch只包裹异步请求

上一篇 下一篇

猜你喜欢

热点阅读