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


Golang errors.New函数代码示例

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


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

示例1: bindAppToServices

func (cmd *Push) bindAppToServices(services []string, app models.Application) error {
	for _, serviceName := range services {
		serviceInstance, err := cmd.serviceRepo.FindInstanceByName(serviceName)

		if err != nil {
			return errors.New(T("Could not find service {{.ServiceName}} to bind to {{.AppName}}",
				map[string]interface{}{"ServiceName": serviceName, "AppName": app.Name}))
		}

		cmd.ui.Say(T("Binding service {{.ServiceName}} to app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.Username}}...",
			map[string]interface{}{
				"ServiceName": terminal.EntityNameColor(serviceInstance.Name),
				"AppName":     terminal.EntityNameColor(app.Name),
				"OrgName":     terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
				"SpaceName":   terminal.EntityNameColor(cmd.config.SpaceFields().Name),
				"Username":    terminal.EntityNameColor(cmd.config.Username())}))

		err = cmd.serviceBinder.BindApplication(app, serviceInstance, nil)

		switch httpErr := err.(type) {
		case errors.HTTPError:
			if httpErr.ErrorCode() == errors.ServiceBindingAppServiceTaken {
				err = nil
			}
		}

		if err != nil {
			return errors.New(T("Could not bind to service {{.ServiceName}}\nError: {{.Err}}",
				map[string]interface{}{"ServiceName": serviceName, "Err": err.Error()}))
		}

		cmd.ui.Ok()
	}
	return nil
}
开发者ID:jasonkeene,项目名称:cli,代码行数:35,代码来源:push.go

示例2: Authenticate

func (uaa UAARepository) Authenticate(credentials map[string]string) error {
	data := url.Values{
		"grant_type": {"password"},
		"scope":      {""},
	}
	for key, val := range credentials {
		data[key] = []string{val}
	}

	err := uaa.getAuthToken(data)
	if err != nil {
		httpError, ok := err.(errors.HTTPError)
		if ok {
			switch {
			case httpError.StatusCode() == http.StatusUnauthorized:
				return errors.New(T("Credentials were rejected, please try again."))
			case httpError.StatusCode() >= http.StatusInternalServerError:
				return errors.New(T("The targeted API endpoint could not be reached."))
			}
		}

		return err
	}

	return nil
}
开发者ID:Reejoshi,项目名称:cli,代码行数:26,代码来源:authentication.go

示例3: Execute

func (cmd *Password) Execute(c flags.FlagContext) error {
	oldPassword := cmd.ui.AskForPassword(T("Current Password"))
	newPassword := cmd.ui.AskForPassword(T("New Password"))
	verifiedPassword := cmd.ui.AskForPassword(T("Verify Password"))

	if verifiedPassword != newPassword {
		return errors.New(T("Password verification does not match"))
	}

	cmd.ui.Say(T("Changing password..."))
	err := cmd.pwdRepo.UpdatePassword(oldPassword, newPassword)

	switch typedErr := err.(type) {
	case nil:
	case errors.HTTPError:
		if typedErr.StatusCode() == 401 {
			return errors.New(T("Current password did not match"))
		}
		return err
	default:
		return err
	}

	cmd.ui.Ok()
	cmd.config.ClearSession()
	cmd.ui.Say(T("Please log in again"))
	return nil
}
开发者ID:jasonkeene,项目名称:cli,代码行数:28,代码来源:passwd.go

示例4: getAppParamsFromManifest

func (cmd *Push) getAppParamsFromManifest(c flags.FlagContext) ([]models.AppParams, error) {
	if c.Bool("no-manifest") {
		return []models.AppParams{}, nil
	}

	var path string
	if c.String("f") != "" {
		path = c.String("f")
	} else {
		var err error
		path, err = os.Getwd()
		if err != nil {
			return nil, errors.New(fmt.Sprint(T("Could not determine the current working directory!"), err))
		}
	}

	m, err := cmd.manifestRepo.ReadManifest(path)

	if err != nil {
		if m.Path == "" && c.String("f") == "" {
			return []models.AppParams{}, nil
		}
		return nil, errors.New(T("Error reading manifest file:\n{{.Err}}", map[string]interface{}{"Err": err.Error()}))
	}

	apps, err := m.Applications()
	if err != nil {
		return nil, errors.New(T("Error reading manifest file:\n{{.Err}}", map[string]interface{}{"Err": err.Error()}))
	}

	cmd.ui.Say(T("Using manifest file {{.Path}}\n",
		map[string]interface{}{"Path": terminal.EntityNameColor(m.Path)}))
	return apps, nil
}
开发者ID:jasonkeene,项目名称:cli,代码行数:34,代码来源:push.go

示例5: processPathCallback

func (cmd *Push) processPathCallback(path string, app models.Application) func(string) error {
	return func(appDir string) error {
		localFiles, err := cmd.appfiles.AppFilesInDir(appDir)
		if err != nil {
			return errors.New(
				T("Error processing app files in '{{.Path}}': {{.Error}}",
					map[string]interface{}{
						"Path":  path,
						"Error": err.Error(),
					}))
		}

		if len(localFiles) == 0 {
			return errors.New(
				T("No app files found in '{{.Path}}'",
					map[string]interface{}{
						"Path": path,
					}))
		}

		cmd.ui.Say(T("Uploading {{.AppName}}...",
			map[string]interface{}{"AppName": terminal.EntityNameColor(app.Name)}))

		err = cmd.uploadApp(app.GUID, appDir, path, localFiles)
		if err != nil {
			return errors.New(T("Error uploading application.\n{{.APIErr}}",
				map[string]interface{}{"APIErr": err.Error()}))
		}
		cmd.ui.Ok()
		return nil
	}
}
开发者ID:jasonkeene,项目名称:cli,代码行数:32,代码来源:push.go

示例6: DownloadFileTo

func DownloadFileTo(owner, repo, file, output string) error {
	if output == "" {
		output = file
	}
	src, err := os.Stat(output)
	if err == nil && src.IsDir() {
		output = path.Join(output, file)
	}
	blobFile := Config.FindBlobFile(BlobFile{
		Name: owner + "/" + repo + "/" + file,
	})
	if blobFile == nil {
		return errors.New(fmt.Sprintf("Cannot find file '%s' in github.", file))
	}
	dataDownloaded, err := GetFile(owner, repo, file)
	if err != nil {
		return err
	}
	shaCalc := sha1.New()
	shaCalc.Write(dataDownloaded)
	shaEncoded := hex.EncodeToString(shaCalc.Sum(nil))
	if shaEncoded != blobFile.InternalSha1 {
		return errors.New("Checksum doesn't match between downloaded file and saved sha")
	}
	return ioutil.WriteFile(output, dataDownloaded, 0644)
}
开发者ID:ArthurHlt,项目名称:github-blob-sender,代码行数:26,代码来源:manage_file.go

示例7: createAppSetFromContextAndManifest

func (cmd *Push) createAppSetFromContextAndManifest(contextApp models.AppParams, manifestApps []models.AppParams) ([]models.AppParams, error) {
	var err error
	var apps []models.AppParams

	switch len(manifestApps) {
	case 0:
		if contextApp.Name == nil {
			return nil, errors.New(
				T("Manifest file is not found in the current directory, please provide either an app name or manifest") +
					"\n\n" +
					commandregistry.Commands.CommandUsage("push"),
			)
		}
		err = addApp(&apps, contextApp)
	case 1:
		manifestApps[0].Merge(&contextApp)
		err = addApp(&apps, manifestApps[0])
	default:
		selectedAppName := contextApp.Name
		contextApp.Name = nil

		if !contextApp.IsEmpty() {
			return nil, errors.New(T("Incorrect Usage. Command line flags (except -f) cannot be applied when pushing multiple apps from a manifest file."))
		}

		if selectedAppName != nil {
			var foundApp bool
			for _, appParams := range manifestApps {
				if appParams.Name != nil && *appParams.Name == *selectedAppName {
					foundApp = true
					err = addApp(&apps, appParams)
				}
			}

			if !foundApp {
				err = errors.New(T("Could not find app named '{{.AppName}}' in manifest", map[string]interface{}{"AppName": *selectedAppName}))
			}
		} else {
			for _, manifestApp := range manifestApps {
				err = addApp(&apps, manifestApp)
			}
		}
	}

	if err != nil {
		return nil, errors.New(T("Error: {{.Err}}", map[string]interface{}{"Err": err.Error()}))
	}

	return apps, nil
}
开发者ID:jasonkeene,项目名称:cli,代码行数:50,代码来源:push.go

示例8: DeleteService

func (repo CloudControllerServiceRepository) DeleteService(instance models.ServiceInstance) (apiErr error) {
	if len(instance.ServiceBindings) > 0 {
		return errors.New("Cannot delete service instance, apps are still bound to it")
	}
	path := fmt.Sprintf("%s/v2/service_instances/%s", repo.config.ApiEndpoint(), instance.Guid)
	return repo.gateway.DeleteResource(path)
}
开发者ID:EthanWu,项目名称:cli,代码行数:7,代码来源:services.go

示例9: Execute

func (cmd *CreateUser) Execute(c flags.FlagContext) error {
	username := c.Args()[0]
	password := c.Args()[1]

	cmd.ui.Say(T("Creating user {{.TargetUser}}...",
		map[string]interface{}{
			"TargetUser":  terminal.EntityNameColor(username),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	err := cmd.userRepo.Create(username, password)
	switch err.(type) {
	case nil:
	case *errors.ModelAlreadyExistsError:
		cmd.ui.Warn("%s", err.Error())
	default:
		return errors.New(T("Error creating user {{.TargetUser}}.\n{{.Error}}",
			map[string]interface{}{
				"TargetUser": terminal.EntityNameColor(username),
				"Error":      err.Error(),
			}))
	}

	cmd.ui.Ok()
	cmd.ui.Say(T("\nTIP: Assign roles with '{{.CurrentUser}} set-org-role' and '{{.CurrentUser}} set-space-role'", map[string]interface{}{"CurrentUser": cf.Name}))
	return nil
}
开发者ID:Reejoshi,项目名称:cli,代码行数:27,代码来源:create_user.go

示例10: createBuildpack

func (cmd CreateBuildpack) createBuildpack(buildpackName string, c flags.FlagContext) (buildpack models.Buildpack, apiErr error) {
	position, err := strconv.Atoi(c.Args()[2])
	if err != nil {
		apiErr = fmt.Errorf(T("Error {{.ErrorDescription}} is being passed in as the argument for 'Position' but 'Position' requires an integer.  For more syntax help, see `cf create-buildpack -h`.", map[string]interface{}{"ErrorDescription": c.Args()[2]}))
		return
	}

	enabled := c.Bool("enable")
	disabled := c.Bool("disable")
	if enabled && disabled {
		apiErr = errors.New(T("Cannot specify both {{.Enabled}} and {{.Disabled}}.", map[string]interface{}{
			"Enabled":  "enabled",
			"Disabled": "disabled",
		}))
		return
	}

	var enableOption *bool
	if enabled {
		enableOption = &enabled
	}
	if disabled {
		disabled = false
		enableOption = &disabled
	}

	buildpack, apiErr = cmd.buildpackRepo.Create(buildpackName, &position, enableOption, nil)

	return
}
开发者ID:vframbach,项目名称:cli,代码行数:30,代码来源:create_buildpack.go

示例11: setAPIEndpoint

func (cmd API) setAPIEndpoint(endpoint string, skipSSL bool, cmdName string) error {
	if strings.HasSuffix(endpoint, "/") {
		endpoint = strings.TrimSuffix(endpoint, "/")
	}

	cmd.config.SetSSLDisabled(skipSSL)

	refresher := coreconfig.APIConfigRefresher{
		Endpoint:     endpoint,
		EndpointRepo: cmd.endpointRepo,
		Config:       cmd.config,
	}

	warning, err := refresher.Refresh()
	if err != nil {
		cmd.config.SetAPIEndpoint("")
		cmd.config.SetSSLDisabled(false)

		switch typedErr := err.(type) {
		case *errors.InvalidSSLCert:
			cfAPICommand := terminal.CommandColor(fmt.Sprintf("%s %s --skip-ssl-validation", cf.Name, cmdName))
			tipMessage := fmt.Sprintf(T("TIP: Use '{{.APICommand}}' to continue with an insecure API endpoint",
				map[string]interface{}{"APICommand": cfAPICommand}))
			return errors.New(T("Invalid SSL Cert for {{.URL}}\n{{.TipMessage}}",
				map[string]interface{}{"URL": typedErr.URL, "TipMessage": tipMessage}))
		default:
			return typedErr
		}
	}

	if warning != nil {
		cmd.ui.Say(terminal.WarningColor(warning.Warn()))
	}
	return nil
}
开发者ID:jasonkeene,项目名称:cli,代码行数:35,代码来源:api.go

示例12: BindRoute

func (routeActor routeActor) BindRoute(app models.Application, route models.Route) error {
	if !app.HasRoute(route) {
		routeActor.ui.Say(T(
			"Binding {{.URL}} to {{.AppName}}...",
			map[string]interface{}{
				"URL":     terminal.EntityNameColor(route.URL()),
				"AppName": terminal.EntityNameColor(app.Name),
			}),
		)

		err := routeActor.routeRepo.Bind(route.GUID, app.GUID)
		switch err := err.(type) {
		case nil:
			routeActor.ui.Ok()
			routeActor.ui.Say("")
			return nil
		case errors.HTTPError:
			if err.ErrorCode() == errors.InvalidRelation {
				return errors.New(T(
					"The route {{.URL}} is already in use.\nTIP: Change the hostname with -n HOSTNAME or use --random-route to generate a new route and then push again.",
					map[string]interface{}{
						"URL": route.URL(),
					}),
				)
			}
		}
		return err
	}
	return nil
}
开发者ID:jasonkeene,项目名称:cli,代码行数:30,代码来源:routes.go

示例13: copyUploadableFiles

func (actor PushActorImpl) copyUploadableFiles(appDir string, uploadDir string) (presentFiles []resources.AppFileResource, hasFileToUpload bool, err error) {
	// Find which files need to be uploaded
	allAppFiles, err := actor.appfiles.AppFilesInDir(appDir)
	if err != nil {
		return
	}

	appFilesToUpload, presentFiles, apiErr := actor.getFilesToUpload(allAppFiles)
	if apiErr != nil {
		err = errors.New(apiErr.Error())
		return
	}
	hasFileToUpload = len(appFilesToUpload) > 0

	// Copy files into a temporary directory and return it
	err = actor.appfiles.CopyFiles(appFilesToUpload, appDir, uploadDir)
	if err != nil {
		return
	}

	// copy cfignore if present
	fileutils.CopyPathToPath(filepath.Join(appDir, ".cfignore"), filepath.Join(uploadDir, ".cfignore")) //error handling?

	return
}
开发者ID:0976254669,项目名称:cli,代码行数:25,代码来源:push.go

示例14: Execute

func (cmd *RenameService) Execute(c flags.FlagContext) error {
	newName := c.Args()[1]
	serviceInstance := cmd.serviceInstanceReq.GetServiceInstance()

	cmd.ui.Say(T("Renaming service {{.ServiceName}} to {{.NewServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"ServiceName":    terminal.EntityNameColor(serviceInstance.Name),
			"NewServiceName": terminal.EntityNameColor(newName),
			"OrgName":        terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
			"SpaceName":      terminal.EntityNameColor(cmd.config.SpaceFields().Name),
			"CurrentUser":    terminal.EntityNameColor(cmd.config.Username()),
		}))
	err := cmd.serviceRepo.RenameService(serviceInstance, newName)

	if err != nil {
		if httpError, ok := err.(errors.HTTPError); ok && httpError.ErrorCode() == errors.ServiceInstanceNameTaken {
			return errors.New(T("{{.ErrorDescription}}\nTIP: Use '{{.CFServicesCommand}}' to view all services in this org and space.",
				map[string]interface{}{
					"ErrorDescription":  httpError.Error(),
					"CFServicesCommand": cf.Name + " " + "services",
				}))
		}
		return err
	}

	cmd.ui.Ok()
	return nil
}
开发者ID:Reejoshi,项目名称:cli,代码行数:28,代码来源:rename_service.go

示例15: waitForJob

func waitForJob(jobUrl, accessToken string, timeout time.Duration) (err error) {
	startTime := time.Now()
	for true {
		if time.Now().Sub(startTime) > timeout && timeout != 0 {
			return errors.NewAsyncTimeoutError(jobUrl)
		}
		var request *Request
		request, err = NewRequest("GET", jobUrl, accessToken, nil)
		response := &JobResource{}
		_, err = gwPerformRequestForJSONResponse(request, response)
		if err != nil {
			return
		}

		switch response.Entity.Status {
		case JOB_FINISHED:
			return
		case JOB_FAILED:
			err = errors.New(response.Entity.ErrorDetails.Description)
			return
		}

		accessToken = request.HttpReq.Header.Get("Authorization")

		time.Sleep(DEFAULT_POLLING_THROTTLE)
	}
	return
}
开发者ID:glyn,项目名称:bloblets,代码行数:28,代码来源:abclient.go


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