duan0065626385 2017-10-20 05:13
浏览 43
已采纳

404响应后继续循环

This maybe a noob question but I've been googling for a while.

I am running in a for loop, for each loop a different api request

jiraClient, err := jira.NewClient(nil, *jiraURL)

if err != nil {
    panic(err)
}

jiraClient.Authentication.SetBasicAuth(*jiraUser, string(jiraPass))

reader := csv.NewReader(*file)
CSVData, err := reader.ReadAll()

if err != nil {
    fmt.Println(err)
    os.Exit(1)
}

lineCount := 1

for _, line := range data {

    //reading CSV

    //this returns 200 for all users found but 404 for not found
    user, resp, _ := jiraClient.User.Get(user) 

    if resp.StatusCode == 200 {
        fmt.Printf("Changed %s to %s
", user.Name, data.user)
    } else {
        // have tried continue, return
    }
}

Every time it gets to a 404 response, the program fails and exits

I've tried a try and catch with no luck.

How can i have it continue?

  • 写回答

1条回答 默认 最新

  • doushouj966020 2017-10-20 12:11
    关注

    This question leaks details that because it earned so much down-votes. I assumed that we are dealing with a Get method of UserService in go-jira.

    The Get method returns error:

    func (s *UserService) Get(username string) (*User, *Response, error)
    

    You are omitting error check and pulling it to a blank identifier. Note that if an error returned with a non-nil value then the *User is nil.

    resp, err := s.client.Do(req, user)
    if err != nil {
        return nil, resp, err
    }
    

    And if even I incorrectly assumed a lib which you are using it is a Go way to handle the situation. The proper way is to check error value and do what you need but not wait until your program face nil pointer dereference.

      user, resp, err := jiraClient.User.Get()
      if err != nil {
          // Do something clever...
      }
    

    Errors are values

    Furthermore error is an interface. So error could contain some useful data or be an object of a concrete type.

    An error variable represents any value that can describe itself as a string. Here is the interface's declaration:

    type error interface {
        Error() string
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上