當前位置: 首頁>>代碼示例>>Golang>>正文


Golang errors.NewAlreadyExists函數代碼示例

本文整理匯總了Golang中github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors.NewAlreadyExists函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewAlreadyExists函數的具體用法?Golang NewAlreadyExists怎麽用?Golang NewAlreadyExists使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了NewAlreadyExists函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: TestAsyncCreateError

func TestAsyncCreateError(t *testing.T) {
	ch := make(chan struct{})
	storage := SimpleRESTStorage{
		injectedFunction: func(obj runtime.Object) (runtime.Object, error) {
			<-ch
			return nil, apierrs.NewAlreadyExists("foo", "bar")
		},
	}
	selfLinker := &setTestSelfLinker{
		t:           t,
		name:        "bar",
		expectedSet: "/prefix/version/foo/bar",
	}
	handler := Handle(map[string]RESTStorage{"foo": &storage}, codec, "/prefix/version", selfLinker)
	handler.(*defaultAPIServer).group.handler.asyncOpWait = 0
	server := httptest.NewServer(handler)
	defer server.Close()

	simple := &Simple{Other: "bar"}
	data, _ := codec.Encode(simple)

	status := expectApiStatus(t, "POST", fmt.Sprintf("%s/prefix/version/foo", server.URL), data, http.StatusAccepted)
	if status.Status != api.StatusWorking || status.Details == nil || status.Details.ID == "" {
		t.Errorf("Unexpected status %#v", status)
	}

	otherStatus := expectApiStatus(t, "GET", fmt.Sprintf("%s/prefix/version/operations/%s", server.URL, status.Details.ID), []byte{}, http.StatusAccepted)
	if !reflect.DeepEqual(status, otherStatus) {
		t.Errorf("Expected %#v, Got %#v", status, otherStatus)
	}

	ch <- struct{}{}
	time.Sleep(time.Millisecond)

	finalStatus := expectApiStatus(t, "GET", fmt.Sprintf("%s/prefix/version/operations/%s?after=1", server.URL, status.Details.ID), []byte{}, http.StatusOK)
	expectedErr := apierrs.NewAlreadyExists("foo", "bar")
	expectedStatus := &api.Status{
		Status:  api.StatusFailure,
		Code:    http.StatusConflict,
		Reason:  "AlreadyExists",
		Message: expectedErr.Error(),
		Details: &api.StatusDetails{
			Kind: "foo",
			ID:   "bar",
		},
	}
	if !reflect.DeepEqual(expectedStatus, finalStatus) {
		t.Errorf("Expected %#v, Got %#v", expectedStatus, finalStatus)
		if finalStatus.Details != nil {
			t.Logf("Details %#v, Got %#v", *expectedStatus.Details, *finalStatus.Details)
		}
	}
	if !selfLinker.called {
		t.Errorf("Never set self link")
	}
}
開發者ID:ericcapricorn,項目名稱:kubernetes,代碼行數:56,代碼來源:apiserver_test.go

示例2: CreateController

// CreateController creates a new ReplicationController.
func (r *Registry) CreateController(controller api.ReplicationController) error {
	err := r.CreateObj(makeControllerKey(controller.ID), controller)
	if tools.IsEtcdNodeExist(err) {
		return errors.NewAlreadyExists("replicationController", controller.ID)
	}
	return err
}
開發者ID:hungld,項目名稱:kubernetes,代碼行數:8,代碼來源:etcd.go

示例3: CreateService

// CreateService creates a new Service.
func (r *Registry) CreateService(svc api.Service) error {
	err := r.CreateObj(makeServiceKey(svc.ID), svc)
	if tools.IsEtcdNodeExist(err) {
		return errors.NewAlreadyExists("service", svc.ID)
	}
	return err
}
開發者ID:hungld,項目名稱:kubernetes,代碼行數:8,代碼來源:etcd.go

示例4: TestErrorsToAPIStatus

func TestErrorsToAPIStatus(t *testing.T) {
	cases := map[error]api.Status{
		errors.NewAlreadyExists("foo", "bar"): {
			Status:  api.StatusFailure,
			Code:    http.StatusConflict,
			Reason:  "AlreadyExists",
			Message: "foo \"bar\" already exists",
			Details: &api.StatusDetails{
				Kind: "foo",
				ID:   "bar",
			},
		},
		errors.NewConflict("foo", "bar", stderrs.New("failure")): {
			Status:  api.StatusFailure,
			Code:    http.StatusConflict,
			Reason:  "Conflict",
			Message: "foo \"bar\" cannot be updated: failure",
			Details: &api.StatusDetails{
				Kind: "foo",
				ID:   "bar",
			},
		},
	}
	for k, v := range cases {
		actual := errToAPIStatus(k)
		if !reflect.DeepEqual(actual, &v) {
			t.Errorf("%s: Expected %#v, Got %#v", k, v, actual)
		}
	}
}
開發者ID:cjnygard,項目名稱:origin,代碼行數:30,代碼來源:errors_test.go

示例5: CreateImage

// CreateImage creates a new image
func (r *Etcd) CreateImage(image *api.Image) error {
	err := r.CreateObj(makeImageKey(image.ID), image)
	if tools.IsEtcdNodeExist(err) {
		return apierrors.NewAlreadyExists("image", image.ID)
	}
	return err
}
開發者ID:rajdavies,項目名稱:origin,代碼行數:8,代碼來源:etcd.go

示例6: TestCheckGeneratedNameError

func TestCheckGeneratedNameError(t *testing.T) {
	expect := errors.NewNotFound("foo", "bar")
	if err := CheckGeneratedNameError(Services, expect, &api.Pod{}); err != expect {
		t.Errorf("NotFoundError should be ignored: %v", err)
	}

	expect = errors.NewAlreadyExists("foo", "bar")
	if err := CheckGeneratedNameError(Services, expect, &api.Pod{}); err != expect {
		t.Errorf("AlreadyExists should be returned when no GenerateName field: %v", err)
	}

	expect = errors.NewAlreadyExists("foo", "bar")
	if err := CheckGeneratedNameError(Services, expect, &api.Pod{ObjectMeta: api.ObjectMeta{GenerateName: "foo"}}); err == nil || !errors.IsServerTimeout(err) {
		t.Errorf("expected try again later error: %v", err)
	}
}
開發者ID:brorhie,項目名稱:panamax-kubernetes-adapter-go,代碼行數:16,代碼來源:create_test.go

示例7: Create

func (m *VirtualStorage) Create(ctx kapi.Context, obj runtime.Object) (runtime.Object, error) {
	if err := rest.BeforeCreate(m.CreateStrategy, ctx, obj); err != nil {
		return nil, err
	}

	role := obj.(*authorizationapi.Role)

	policy, err := m.EnsurePolicy(ctx)
	if err != nil {
		return nil, err
	}
	if _, exists := policy.Roles[role.Name]; exists {
		return nil, kapierrors.NewAlreadyExists("Role", role.Name)
	}

	role.ResourceVersion = policy.ResourceVersion
	policy.Roles[role.Name] = role
	policy.LastModified = util.Now()

	if err := m.PolicyStorage.UpdatePolicy(ctx, policy); err != nil {
		return nil, err
	}

	return role, nil
}
開發者ID:pombredanne,項目名稱:atomic-enterprise,代碼行數:25,代碼來源:virtual_storage.go

示例8: CreateBuild

// CreateBuild creates a new Build.
func (r *EtcdRegistry) CreateBuild(build *api.Build) error {
	err := r.CreateObj(makeBuildKey(build.ID), build)
	if tools.IsEtcdNodeExist(err) {
		return errors.NewAlreadyExists("build", build.ID)
	}
	return err
}
開發者ID:lmiccini,項目名稱:origin,代碼行數:8,代碼來源:etcdregistry.go

示例9: CreateBuildConfig

// CreateBuildConfig creates a new BuildConfig.
func (r *EtcdRegistry) CreateBuildConfig(config *api.BuildConfig) error {
	err := r.CreateObj(makeBuildConfigKey(config.ID), config)
	if tools.IsEtcdNodeExist(err) {
		return errors.NewAlreadyExists("buildConfig", config.ID)
	}
	return err
}
開發者ID:lmiccini,項目名稱:origin,代碼行數:8,代碼來源:etcdregistry.go

示例10: InterpretCreateError

// InterpretCreateError converts a generic etcd error on a create
// operation into the appropriate API error.
func InterpretCreateError(err error, kind, name string) error {
	switch {
	case tools.IsEtcdNodeExist(err):
		return errors.NewAlreadyExists(kind, name)
	default:
		return err
	}
}
開發者ID:eghobo,項目名稱:kubedash,代碼行數:10,代碼來源:etcd.go

示例11: CreateImageRepository

// CreateImageRepository registers the given ImageRepository.
func (r *Etcd) CreateImageRepository(repo *api.ImageRepository) error {
	err := r.CreateObj(makeImageRepositoryKey(repo.ID), repo)
	if err != nil && tools.IsEtcdNodeExist(err) {
		return apierrors.NewAlreadyExists("imageRepository", repo.ID)
	}

	return err
}
開發者ID:rajdavies,項目名稱:origin,代碼行數:9,代碼來源:etcd.go

示例12: Create

func (r *REST) Create(ctx kapi.Context, obj runtime.Object) (runtime.Object, error) {

	if err := rest.BeforeCreate(projectrequestregistry.Strategy, ctx, obj); err != nil {
		return nil, err
	}

	projectRequest := obj.(*projectapi.ProjectRequest)

	if _, err := r.openshiftClient.Projects().Get(projectRequest.Name); err == nil {
		return nil, kapierror.NewAlreadyExists("project", projectRequest.Name)
	}

	projectName := projectRequest.Name
	projectAdmin := ""
	if userInfo, exists := kapi.UserFrom(ctx); exists {
		projectAdmin = userInfo.GetName()
	}

	template, err := r.getTemplate()
	if err != nil {
		return nil, err
	}

	for i := range template.Parameters {
		switch template.Parameters[i].Name {
		case ProjectAdminUserParam:
			template.Parameters[i].Value = projectAdmin
		case ProjectDescriptionParam:
			template.Parameters[i].Value = projectRequest.Description
		case ProjectDisplayNameParam:
			template.Parameters[i].Value = projectRequest.DisplayName
		case ProjectNameParam:
			template.Parameters[i].Value = projectName
		}
	}

	list, err := r.openshiftClient.TemplateConfigs(kapi.NamespaceDefault).Create(template)
	if err != nil {
		return nil, err
	}
	if err := utilerrors.NewAggregate(runtime.DecodeList(list.Objects, kapi.Scheme)); err != nil {
		return nil, err
	}

	bulk := configcmd.Bulk{
		Mapper: latest.RESTMapper,
		Typer:  kapi.Scheme,
		RESTClientFactory: func(mapping *meta.RESTMapping) (resource.RESTClient, error) {
			return r.openshiftClient, nil
		},
	}
	if err := utilerrors.NewAggregate(bulk.Create(&kapi.List{Items: list.Objects}, projectName)); err != nil {
		return nil, err
	}

	return r.openshiftClient.Projects().Get(projectName)
}
開發者ID:pombredanne,項目名稱:atomic-enterprise,代碼行數:57,代碼來源:delegated.go

示例13: InterpretCreateError

// InterpretCreateError converts a generic etcd error on a create
// operation into the appropriate API error.
func InterpretCreateError(err error, kind, name string) error {
	switch {
	case tools.IsEtcdNodeExist(err):
		return errors.NewAlreadyExists(kind, name)
	case errors.IsAPIStatusError(err):
		return err
	default:
		return errors.NewInternalError(err)
	}
}
開發者ID:alexmavr,項目名稱:dashboard,代碼行數:12,代碼來源:etcd.go

示例14: transformResponse

// transformResponse converts an API response into a structured API object.
func (r *Request) transformResponse(resp *http.Response, req *http.Request) ([]byte, bool, error) {
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, false, err
	}

	// Did the server give us a status response?
	isStatusResponse := false
	var status api.Status
	if err := r.codec.DecodeInto(body, &status); err == nil && status.Status != "" {
		isStatusResponse = true
	}

	switch {
	case resp.StatusCode == http.StatusSwitchingProtocols:
		// no-op, we've been upgraded
	case resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent:
		if !isStatusResponse {
			var err error = &UnexpectedStatusError{
				Request:  req,
				Response: resp,
				Body:     string(body),
			}
			// TODO: handle other error classes we know about
			switch resp.StatusCode {
			case http.StatusConflict:
				if req.Method == "POST" {
					err = errors.NewAlreadyExists(r.resource, r.resourceName)
				} else {
					err = errors.NewConflict(r.resource, r.resourceName, err)
				}
			case http.StatusNotFound:
				err = errors.NewNotFound(r.resource, r.resourceName)
			case http.StatusBadRequest:
				err = errors.NewBadRequest(err.Error())
			}
			return nil, false, err
		}
		return nil, false, errors.FromObject(&status)
	}

	// If the server gave us a status back, look at what it was.
	if isStatusResponse && status.Status != api.StatusSuccess {
		// "Working" requests need to be handled specially.
		// "Failed" requests are clearly just an error and it makes sense to return them as such.
		return nil, false, errors.FromObject(&status)
	}

	created := resp.StatusCode == http.StatusCreated
	return body, created, err
}
開發者ID:brorhie,項目名稱:panamax-kubernetes-adapter-go,代碼行數:54,代碼來源:request.go

示例15: TestErroredConflictedCreateServices

func TestErroredConflictedCreateServices(t *testing.T) {
	servicesSetup()
	te.CreateRCError = kerrors.NewAlreadyExists("thing", "name")
	sd, err := adapter.CreateServices(services)

	assert.Len(t, sd, 0)
	pmxErr, ok := err.(*pmxadapter.Error)
	if assert.Error(t, pmxErr) && assert.True(t, ok) {
		assert.Equal(t, te.CreateRCError.Error(), pmxErr.Message)
		assert.Equal(t, http.StatusConflict, pmxErr.Code)
	}
}
開發者ID:brorhie,項目名稱:panamax-kubernetes-adapter-go,代碼行數:12,代碼來源:create_test.go


注:本文中的github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors.NewAlreadyExists函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。