如何到达课堂之外并中断课堂继续学习?

时间:2019-06-06 12:41:19

标签: javascript node.js axios es6-class

我想中断该类并在该类遇到问题并退还给我指定的错误时结束该类的继续工作。

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
                        })) 
                    }
                })
        })
    }
}

在上面的代码中,我想让类返回我的自定义错误,并且在无法从外部接收IP时不再继续。但它没有返回错误,而是继续出现错误的类。我该怎么办?

2 个答案:

答案 0 :(得分:0)

在构造函数中,您无法返回错误,而不是直接使用您的fetchIP方法

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

答案 1 :(得分:0)

让我们尝试一下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));