当前位置: 首页>>代码示例>>Golang>>正文


Golang adaptor.NewError函数代码示例

本文整理汇总了Golang中github.com/sendgrid/chaos/adaptor.NewError函数的典型用法代码示例。如果您正苦于以下问题:Golang NewError函数的具体用法?Golang NewError怎么用?Golang NewError使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NewError函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: EditUserProfile

func (a *Adaptor) EditUserProfile(userProfile *client.UserProfile) (bool, *adaptor.AdaptorError) {
	var editSuccess int

	params, queryErr := query.Values(userProfile)

	if queryErr != nil {
		ln.Err("error query user profile", ln.Map{"err": queryErr.Error()})
		return false, adaptor.NewError("error query user profile")
	}

	err := a.apidClient.DoFunction("editUserProfile", params, &editSuccess)

	if err != nil {
		ln.Err("error updating user profile", ln.Map{"err": err.Error(), "user_profile": userProfile})
		return false, adaptor.NewError("error updating user profile")
	}

	if editSuccess == 0 {
		// check if the user exists
		user, adaptorError := a.GetUserProfile(userProfile.UserID)

		if adaptorError != nil {
			ln.Err("error when getting user profile", ln.Map{"err": adaptorError.Error(), "user_id": userProfile.UserID})
			return false, adaptor.NewError("error when getting user profile")
		}
		if user == nil {
			return false, adaptor.NewErrorWithStatus("user profile not found", http.StatusNotFound)
		}
		// no fields were changed
		return true, nil
	}

	return true, nil
}
开发者ID:john-cai,项目名称:tools,代码行数:34,代码来源:provision.go

示例2: PackageIDFromUUID

func (a *Adaptor) PackageIDFromUUID(packageUUID string) (int, *adaptor.AdaptorError) {
	params := url.Values{
		"tableName": []string{"package"},
		"where":     []string{fmt.Sprintf(`{"uuid":"%s"}`, packageUUID)},
	}

	var packages []struct {
		ID int `json:"id"`
	}

	err := a.apidClient.DoFunction("get", params, &packages)

	if err != nil {
		ln.Err("error calling get for user package", ln.Map{"error": err.Error(), "uuid": packageUUID})
		formattedErr := adaptor.NewError("unable to process request")
		return -1, formattedErr

	}

	if len(packages) != 1 {
		ln.Err("did not get one result back from get call for user package", ln.Map{"uuid": packageUUID})
		formattedErr := adaptor.NewError(ErrorNoPackagesFound)
		return -1, formattedErr
	}

	return packages[0].ID, nil
}
开发者ID:john-cai,项目名称:tools,代码行数:27,代码来源:user_package.go

示例3: insertNewCompetitor

func (a *Adaptor) insertNewCompetitor(userID int, otherProvider string) (int, *adaptor.AdaptorError) {
	addParams := url.Values{
		"user_id":    []string{strconv.Itoa(userID)},
		"competitor": []string{otherProvider},
	}

	columns := NewCrudColumns()
	columns.AddColumns(addParams)

	// add new user package
	var ok string
	err := a.apidClient.DoFunction("add", url.Values{
		"tableName": []string{"competitors"},
		"values":    []string{columns.String()},
	}, &ok)

	if err != nil {
		ln.Err("unable to add to competitor table", ln.Map{"err": err.Error()})
		return 0, adaptor.NewError("internal data storage error")
	}

	if ok != "success" {
		ln.Err("error adding to competitor table", ln.Map{"err": fmt.Sprintf("%s - %s", ok, err.Error())})
		return 0, adaptor.NewError("internal data storage error")
	}

	return a.getInvalidCompetitorID(userID, otherProvider)
}
开发者ID:john-cai,项目名称:tools,代码行数:28,代码来源:user_package.go

示例4: AssignExternalIP

func (a *Adaptor) AssignExternalIP(userID int, ip string) *adaptor.AdaptorError {

	var eIP []ExternalIP

	err := a.apidClient.DoFunction("getExternalIp", url.Values{"ip": []string{ip}, "exclude_whitelabels": []string{strconv.Itoa(0)}}, &eIP)

	if err != nil {
		ln.Err("error when getting external ips of user", ln.Map{"error": err.Error(), "user_id": userID, "ip": ip})
		return adaptor.NewError("error when getting external ips of user")

	}
	params := url.Values{
		"ip":              []string{ip},
		"reseller_id":     []string{strconv.Itoa(userID)},
		"server_name_id":  []string{strconv.Itoa(eIP[0].ServerID)},
		"in_sender_score": []string{strconv.Itoa(eIP[0].InSenderScore)},
	}

	var result int
	err = a.apidClient.DoFunction("editExternalIp", params, &result)
	if err != nil {
		ln.Err("error when editing external ip of user", ln.Map{"error": err.Error(), "user_id": userID, "ip": ip})
		return adaptor.NewError("error when editing external ip of user")
	}

	return nil

}
开发者ID:john-cai,项目名称:tools,代码行数:28,代码来源:ip.go

示例5: getValidCompetitorID

func (a *Adaptor) getValidCompetitorID(otherProvider string) (int, *adaptor.AdaptorError) {
	params := url.Values{
		"tableName": []string{"competitors"},
		"where":     []string{fmt.Sprintf(`{"competitor":"%s"}`, otherProvider)},
	}
	competition := []competitor{}

	err := a.apidClient.DoFunction("get", params, &competition)
	if err != nil {
		ln.Err("unable to get competitors value", ln.Map{"err": err.Error()})
		return 0, adaptor.NewError("internal data storage error")
	}

	if len(competition) == 0 {
		return 0, nil
	}

	if len(competition) >= 1 {
		// only return a valid competitor id if there is no user id
		for _, c := range competition {
			if c.UserID == 0 {
				return c.UserID, nil
			}
		}
	}
	// if we got here, it means all entries in the competitor table were tied to a user id
	// meaning the BI team has not vetted the entry
	ln.Info("no valid competitor found", nil)
	return 0, adaptor.NewError("internal data storage error")
}
开发者ID:john-cai,项目名称:tools,代码行数:30,代码来源:user_package.go

示例6: ChangePackage

func (b *Adaptor) ChangePackage(userID int, packageID int, immediateChange bool, addOn ...string) *adaptor.AdaptorError {
	var effectiveDate time.Time

	if immediateChange {
		effectiveDate = time.Now()
	} else {
		effectiveDate = FindDowngradeDate(time.Now())
	}

	putBody := BossUpdatePackageParams{
		PackageID:     packageID,
		AddOn:         addOn,
		EffectiveDate: effectiveDate.Format("2006-01-02"),
	}

	updatePackageURL := fmt.Sprintf("%s/billing_provider_api/v1/users/%d/user_package", b.bossURL, userID)

	authToken := fmt.Sprintf("token=%s", b.authToken)

	client := &http.Client{}

	data, err := json.Marshal(putBody)

	if err != nil {
		ln.Err("something went wrong marshalling change package put body", ln.Map{"error": err.Error(), "user_id": userID})
		return adaptor.NewError("could not marshal put body")
	}

	req, err := http.NewRequest("PUT", updatePackageURL, bytes.NewReader(data))
	if err != nil {
		ln.Err("something went wrong creating http request for boss update package", ln.Map{"error": err.Error()})
		return adaptor.NewError("could not create put request")
	}
	req.Header.Set("Authorization", authToken)
	req.Header.Set("Content-Type", "application/json")

	curl := fmt.Sprintf("curl -v -X PUT %s -d '%s' --header 'Authorization: <auth token>' --header 'Content-Type: application/json'", updatePackageURL, string(data))
	resp, err := client.Do(req)

	if err != nil {
		ln.Err(fmt.Sprintf("something went wrong executing http request to boss update user package endpoint, %s", curl), ln.Map{"error": err.Error()})
		return adaptor.NewError("error when calling PUT")
	}

	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		b, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			ln.Err(fmt.Sprintf("Error reading response body, %s", curl), ln.Map{"error": err.Error(), "boss_status_code": resp.StatusCode})
			return adaptor.NewError("could not read response body")
		}

		ln.Err(fmt.Sprintf("Error posting to subscriptions, %s", curl), ln.Map{"status_code": resp.StatusCode, "response_body": string(b), "user_id": userID, "url": updatePackageURL})

		return adaptor.NewError("error when calling internal service")
	}

	return nil
}
开发者ID:john-cai,项目名称:tools,代码行数:60,代码来源:boss_client.go

示例7: SetUserPackage

func (a *Adaptor) SetUserPackage(userID int, packageID int) *adaptor.AdaptorError {
	var delSuccess int
	var userPackage string
	packageIDString := strconv.Itoa(packageID)

	pkg, adaptorErr := a.GetPackage(packageID)
	if adaptorErr != nil {
		return adaptorErr
	}

	// delete the user's old package
	err := a.apidClient.DoFunction("delete", url.Values{
		"tableName": []string{"user_package"},
		"where":     []string{`{"user_id" : "` + strconv.Itoa(userID) + `"}`},
	}, &delSuccess)

	if err != nil {
		ln.Err("Something went wrong trying to delete the user's current package", ln.Map{"error": err.Error(), "user_id": userID})
		return adaptor.NewError("Something went wrong trying to delete the user's current package")
	}

	params := url.Values{
		"user_id":          []string{strconv.Itoa(userID)},
		"status":           []string{strconv.Itoa(UserStatusSendGridPaid)},
		"package_id":       []string{packageIDString},
		"package_group_id": []string{strconv.Itoa(pkg.GroupID)},
		"package_status":   []string{strconv.Itoa(PackageStatusActive)},
		"start_date":       []string{time.Now().Format("2006-01-02")},
		"end_date":         []string{now.New(time.Now().AddDate(0, 1, 0)).BeginningOfMonth().Format("2006-01-02")},
		"subusers_limit":   []string{strconv.Itoa(DefaultSubuserLimit)},
		"updated_at":       []string{time.Now().String()},
	}

	columns := NewCrudColumns()
	columns.AddColumns(params)

	// add new user package
	err = a.apidClient.DoFunction("add", url.Values{
		"tableName": []string{"user_package"},
		"values":    []string{columns.String()},
	}, &userPackage)

	if err != nil {
		ln.Err("Something went wrong trying to add a package for the user", ln.Map{"error": err.Error(), "user_id": userID, "package_id": packageID})
		return adaptor.NewError("Something went wrong trying to add the user's package")

	}

	return nil
}
开发者ID:john-cai,项目名称:tools,代码行数:50,代码来源:user_package.go

示例8: TestCreateUserError

func TestCreateUserError(t *testing.T) {
	ln.SetOutput(ioutil.Discard, "test_logger")

	expectedNewUserID := 1234

	// value to be passed into apid
	expectedUsername := "test_user"

	// expected output from apidadaptor
	expectedErr := adaptor.NewError("error when adding user")

	fakeClient := clientfakes.NewFakeClient()
	fakeClient.RegisterFunction("addUser", func(params url.Values) (interface{}, error) {
		username := params.Get("username")
		if username == expectedUsername {
			return 0, fmt.Errorf("some apid error")
		}
		return expectedNewUserID, nil
	})

	adaptor := New(fakeClient)

	_, adaptorErr := adaptor.CreateUser(
		client.Signup{
			Username: expectedUsername,
			Email:    "[email protected]",
			Password: "asdfasdf",
		})

	if assert.NotNil(t, adaptorErr, adaptorErr.Error()) {
		assert.Equal(t, expectedErr.Error(), adaptorErr.Error())
		assert.Equal(t, expectedErr.SuggestedStatusCode, adaptorErr.SuggestedStatusCode)
	}
}
开发者ID:john-cai,项目名称:tools,代码行数:34,代码来源:signup_test.go

示例9: InsertDowngradeToFreeReason

func (a *Adaptor) InsertDowngradeToFreeReason(userID int, reason string) *adaptor.AdaptorError {
	reasonID, adaptorErr := a.getReasonID(reason)
	if adaptorErr != nil {
		return adaptorErr
	}

	params := url.Values{
		"user_id":    []string{strconv.Itoa(userID)},
		"moving":     []string{"0"},
		"event_type": []string{"Downgrade to Free"},
		"reason":     []string{strconv.Itoa(reasonID)},
	}

	columns := NewCrudColumns()
	columns.AddColumns(params)

	var ok string
	err := a.apidClient.DoFunction("add", url.Values{
		"tableName": []string{"user_churn"},
		"values":    []string{columns.String()},
	}, &ok)

	if err != nil {
		ln.Info("unable to call apid add on user_churn", ln.Map{"err": err.Error(), "user_id": userID})
		return adaptor.NewError("internal data storage error")
	}

	if ok != "success" {
		ln.Info("unexpected response from apid add on user_churn", ln.Map{"err": fmt.Sprintf("got '%s', want 'success'", ok), "user_id": userID})
	}

	return nil
}
开发者ID:john-cai,项目名称:tools,代码行数:33,代码来源:user_package.go

示例10: ValidateIPs

func (a *Adaptor) ValidateIPs(userID int, ips []string) (bool, *adaptor.AdaptorError) {
	var formattedErr *adaptor.AdaptorError
	if len(ips) < 1 {
		formattedErr = adaptor.NewErrorWithStatus("No ips provided", http.StatusBadRequest)
		return false, formattedErr
	}

	params := url.Values{
		"userid":  []string{strconv.Itoa(userID)},
		"ip_list": ips,
	}

	var validIPs int
	err := a.apidClient.DoFunction("validateExternalIps", params, &validIPs)

	if err != nil {
		formattedErr = adaptor.NewError(err.Error())
		if strings.Contains(err.Error(), "ips were invalid") {
			formattedErr = adaptor.NewErrorWithStatus("One or more ips were invalid", http.StatusBadRequest)
		}
		return false, formattedErr
	}

	if validIPs < 1 {
		formattedErr = adaptor.NewErrorWithStatus("User does not have any IPs", http.StatusNotFound)
		return false, formattedErr
	}

	return true, nil
}
开发者ID:john-cai,项目名称:tools,代码行数:30,代码来源:ip.go

示例11: CollectBalance

func (b *Adaptor) CollectBalance(userID int) *adaptor.AdaptorError {
	ln.Debug("Boss CollectBalance()", ln.Map{"account ID": userID})

	authToken := fmt.Sprintf("token=%s", b.authToken)

	client := &http.Client{}

	accountCollectURL, err := b.urls.accountCollectURL(userID)

	if err != nil {
		ln.Err("error when collecting balance, could not get url", ln.Map{"error": err.Error(), "user_id": userID})
		return adaptor.NewError("could not get the collect url")
	}

	req, err := http.NewRequest("PUT", accountCollectURL, nil)
	if err != nil {
		ln.Err("something went wrong creating http request for boss collect", ln.Map{"error": err.Error()})
		return adaptor.NewError("could not create http request")
	}
	req.Header.Set("Authorization", authToken)
	req.Header.Set("Content-Type", "application/json")

	curl := fmt.Sprintf("curl -v -X PUT %s --header 'Authorization: <auth token>' --header 'Content-Type: application/json'", accountCollectURL)
	resp, err := client.Do(req)

	if err != nil {
		ln.Err(fmt.Sprintf("something went wrong executing http request to boss collect endpoint, %s", curl), ln.Map{"error": err.Error()})
		return adaptor.NewError("could not execute request to boss collect endpoint")
	}

	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		respBody, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			ln.Err(fmt.Sprintf("Error to read response body, %s", curl), ln.Map{"error": err.Error(), "boss_status_code": resp.StatusCode})
			return adaptor.NewError("could not read response body")
		}

		ln.Err(fmt.Sprintf("Error putting to collect, %s", curl), ln.Map{"status_code": resp.StatusCode, "response_body": string(respBody), "user_id": userID, "url": accountCollectURL})

		return adaptor.NewError("error when calling internal service")
	}

	return nil
}
开发者ID:john-cai,项目名称:tools,代码行数:46,代码来源:boss_client.go

示例12: SetCreditLimits

func (a *Adaptor) SetCreditLimits(userID int, credits int, period string) (int, *adaptor.AdaptorError) {
	var success int
	err := a.apidClient.DoFunction("setUserCreditLimit", url.Values{
		"userid":     []string{strconv.Itoa(userID)},
		"credits":    []string{strconv.Itoa(credits)},
		"period":     []string{period},
		"last_reset": []string{time.Now().Format("2006-01-02")},
	}, &success)

	if err != nil {
		return 0, adaptor.NewError(err.Error())
	}
	if success == 0 {
		return 0, adaptor.NewError("could not set credit limit settings")
	}

	return success, nil
}
开发者ID:john-cai,项目名称:tools,代码行数:18,代码来源:credit_limits.go

示例13: CouponInfo

func (a *Adaptor) CouponInfo(couponCode string) (client.Coupon, *adaptor.AdaptorError) {
	response := make([]client.Coupon, 1)
	err := a.apidClient.DoFunction("get", url.Values{
		"tableName": []string{"coupon"},
		"where":     []string{`{"code" : "` + couponCode + `"}`},
	}, &response)

	if err != nil {
		return client.Coupon{}, adaptor.NewError(err.Error())
	}

	if len(response) == 0 {
		return client.Coupon{}, adaptor.NewError("No coupons returned when searching for coupon code: " + couponCode)
	}
	couponInfo := response[0]

	return couponInfo, nil
}
开发者ID:john-cai,项目名称:tools,代码行数:18,代码来源:coupon.go

示例14: AssignFirstIP

// Get the first available IP and assign it to the user.  Set that IP as the user send IP
func (a *Adaptor) AssignFirstIP(userID int) *adaptor.AdaptorError {
	locations, err := a.getFirstIPLocation()

	if len(locations) == 0 {
		ln.Info("no locations found for first_ip policy", ln.Map{"locations": locations})
		return adaptor.NewError("no locations found for first_ip policy")
	}

	if err != nil {
		ln.Err("error when getting server locations", ln.Map{"error": err.Error()})
		return adaptor.NewError("error when getting server locations")
	}

	r := rand.New(rand.NewSource(time.Now().Unix()))

	params := url.Values{
		"userid":          []string{strconv.Itoa(userID)},
		"limit":           []string{strconv.Itoa(1)},
		"server_location": []string{strconv.Itoa(locations[r.Intn(len(locations))])},
	}

	// Grab the first available IP and immediately assign it to the user
	var IP []string
	apidErr := a.apidClient.DoFunction("assignBestAvailableOp", params, &IP)
	if apidErr != nil {
		ln.Err("error assigning best ips", ln.Map{"error": apidErr.Error(), "params": params})
		return adaptor.NewError("error assigning best available ips")
	}

	if len(IP) == 0 {
		ln.Info("no available ips", ln.Map{"locations": locations})
		return adaptor.NewError("no available ips")
	}

	// assign ip to user send ip
	_, err = a.AddUserSendIP(userID, IP[0])
	if err != nil {
		ln.Err("could not add ip to user send ips table", ln.Map{"err": err.Error(), "user_id": userID})
		return adaptor.NewError("could not add ip to user send ips table")
	}

	return nil
}
开发者ID:john-cai,项目名称:tools,代码行数:44,代码来源:ip.go

示例15: AddUserFingerprint

func (a *Adaptor) AddUserFingerprint(talon TalonFingerprint) (bool, *adaptor.AdaptorError) {
	var success string

	v, queryErr := query.Values(talon)

	if queryErr != nil {
		ln.Err("error query talon", ln.Map{"err": queryErr.Error()})
		return false, adaptor.NewError("error query talon")
	}

	//turn timezone into string
	tz, err := json.Marshal(talon.Timezone)

	if err != nil {
		ln.Err("error when parsing talon timezone", ln.Map{"err": err.Error()})
		return false, adaptor.NewError("error parsing timezone")
	}

	v.Set("timezone", string(tz))

	columns := NewCrudColumns()
	columns.AddColumns(v)
	addErr := a.apidClient.DoFunction("add", url.Values{
		"tableName": []string{"user_fingerprints"},
		"values":    []string{columns.String()},
	}, &success)

	if addErr != nil {
		if strings.Contains(addErr.Error(), "key exists") {
			return true, nil
		}
		ln.Err("error adding user fingerprint", ln.Map{"err": addErr.Error()})
		formattedErr := adaptor.NewError("error adding user fingerprint")
		return false, formattedErr
	}

	if success == "success" {
		return true, nil
	}

	return false, adaptor.NewError("could not add user fingerprint")
}
开发者ID:john-cai,项目名称:tools,代码行数:42,代码来源:provision.go


注:本文中的github.com/sendgrid/chaos/adaptor.NewError函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。