请问golang中如何处理这种场景的异常?

package requests

请问golang中如何处理这种场景的异常?
可以看到有两个err 的处理没有实现 当用户输入错误的url 比如网址不存在 时候会直接panic

func Request(params *Params, config *config.Config) interface{} {    // 这里的接收 必须使用 return response.Response(body, params.Method, err)

    paramsJson, _ := json.Marshal(params)

    req, err := http.NewRequest("POST", config.Url, bytes.NewBuffer(paramsJson))

    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}

    resp, err := client.Do(req)
    fmt.Println(err.Error())

    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)

    // 处理响应 将err传入到这个方法中有其他逻辑处理
    return response.Response(body, params.Method, err)
}

讨论数量: 1

方式一:

package requests

func Request(params *Params, config *config.Config) interface{} {    // 这里的接收 必须使用 return response.Response(body, params.Method, err)

    paramsJson, _ := json.Marshal(params)

    req, err := http.NewRequest("POST", config.Url, bytes.NewBuffer(paramsJson))
    if err!=nil {
        //这里nil根据实际需求调整
        return response.Response(nil, params.Method, err)
    }

    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}

    resp, err := client.Do(req)
    if err!=nil {
        return response.Response(nil, params.Method, err)
    }
    fmt.Println(err.Error())

    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)

    // 处理响应 将err传入到这个方法中有其他逻辑处理
    return response.Response(body, params.Method, err)
}

方式二:

package requests

func Request(params *Params, config *config.Config) (interface{},error) { //添加一个返回参数

    paramsJson, _ := json.Marshal(params)

    req, err := http.NewRequest("POST", config.Url, bytes.NewBuffer(paramsJson))
    if err!=nil {
        return nil,err
    }
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}

    resp, err := client.Do(req)
    if err!=nil {
        return nil,err
    }
    fmt.Println(err.Error())

    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)

    // 处理响应 将err传入到这个方法中有其他逻辑处理
    return response.Response(body, params.Method, err),nil
}
2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!