如何到达 class 之外并从继续中中断 class?

How to reach outside the class and break class from continue?

我想打破 class 并结束 class 在 class 运行 出现问题时继续 class 并 return 我指定的错误.

class OnlineVisitors {
    constructor() {
        // get VisitorIP
        this.fetchIP().then(ip => this.IP = ip).catch(err=>{
            return err
        });
    }
    async fetchIP() {
        return new Promise(async (resolve, reject) => {
            await axios.get('https://api.ipgeolocation.io/getip')
                .then(res => resolve(res.data.ip))
                .catch(error=>{
                    if (error.response) {
                        return reject(this.ErrorModel({
                            message:'The request was made and the server responded with error',
                            sourceCode:'getIPRequest',
                            errorDetail:error.response.data
                        }))
                        } else if (error.request) {
                        return reject(this.ErrorModel({
                            message:'The request was made but no response was received',
                            sourceCode:'getIPRequest',
                            errorDetail:error.request
                        }))
                        } else {
                        return reject(this.ErrorModel({
                            message:'Something happened in setting up the request that triggered an Error',
                            sourceCode:'getIPRequest',
                            errorDetail:error.message
                        })) 
                    }
                })
        })
    }
}

在上面的代码中,我想 class return 我的自定义错误并且在无法从外部接收 IP 时不要继续。但它没有 return 错误,它继续 class 错误。我该怎么办?

在你的构造函数中,你不能return错误,而是直接使用你的 fetchIP 方法

let x = new OnlineVisitors()
         .fetchIP()
         .then()
          .catch((err) => {
             //handle the err 
          })

让我们试试 try/catch。例如:

  1 const axios = () => new Promise((resolve, reject) => setTimeout(() => reject({ response:  "Error wirh" }), 2000));
  2 
  3 class SimpleClass {
  4         async fetchIp() {
  5           console.log("Tests");
  6           try {
  7             return await axios();
  8           } catch (e) {
  9             if (e.response) {
 10                 // do anything
 11                return new Error("Error on response");
 12             } else if (e.request) {
 13                 // do anything
 14             } else {
 15                 // do anything
 16             }
 17           }
 18         }
 19 }       
 20 
 21 new SimpleClass().fetchIp()
 22   .then(res => console.log(res))
 23   .catch(err => console.log(err));