• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang errors.New函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: ParseTimeInterval

func ParseTimeInterval(source string) (time.Duration, error) {
	matches := intervalRegex.FindStringSubmatch(strings.ToLower(source))

	if matches == nil {
		return 0, errors.New("Invalid time interval " + source)
	}

	val, err := strconv.Atoi(matches[1])

	if err != nil {
		return 0, err
	}

	switch matches[2] {
	case "s":
		return time.Duration(val) * time.Second, nil

	case "m":
		return time.Duration(val) * time.Second * 60, nil

	case "h":
		return time.Duration(val) * time.Second * 60 * 60, nil

	case "d":
		return time.Duration(val) * time.Second * 60 * 60 * 24, nil

	case "w":
		return time.Duration(val) * time.Second * 60 * 60 * 24 * 7, nil

	default:
		return 0, errors.New("Invalid time interval " + source)
	}
}
开发者ID:nagyistge,项目名称:gotelemetry_agent,代码行数:33,代码来源:interval.go


示例2: Run

func (this *MemeOCR) Run(image string) (*OCRResult, error) {
	imageTif := fmt.Sprintf("%s_meme.jpg", image)
	outText := fmt.Sprintf("%s_meme", image)
	preprocessingArgs := []string{image, "-resize", "400%", "-fill", "black", "-fuzz", "10%", "+opaque", "#FFFFFF", imageTif}
	tesseractArgs := []string{"-l", "meme", imageTif, outText}

	err := runProcessorCommand(GetExecPath(), preprocessingArgs)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("Meme preprocessing command failed with error = %v", err))
	}
	defer os.Remove(imageTif)

	err = runProcessorCommand("tesseract", tesseractArgs)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("Meme tesseract command failed with error = %v", err))
	}
	defer os.Remove(outText + ".txt")

	text, err := ioutil.ReadFile(outText + ".txt")
	if err != nil {
		return nil, err
	}

	result := strings.ToLower(strings.TrimSpace(string(text[:])))

	return newOCRResult(this.name, result), nil
}
开发者ID:rizzles,项目名称:convert,代码行数:27,代码来源:ocrcommands.go


示例3: UnmarshalJSON

func (this *OutboundConnectionConfig) UnmarshalJSON(data []byte) error {
	type JsonConnectionConfig struct {
		Protocol      string                   `json:"protocol"`
		SendThrough   *v2net.AddressJson       `json:"sendThrough"`
		StreamSetting *internet.StreamSettings `json:"streamSettings"`
		Settings      json.RawMessage          `json:"settings"`
	}
	jsonConfig := new(JsonConnectionConfig)
	if err := json.Unmarshal(data, jsonConfig); err != nil {
		return errors.New("Point: Failed to parse outbound config: " + err.Error())
	}
	this.Protocol = jsonConfig.Protocol
	this.Settings = jsonConfig.Settings

	if jsonConfig.SendThrough != nil {
		address := jsonConfig.SendThrough.Address
		if address.Family().IsDomain() {
			return errors.New("Point: Unable to send through: " + address.String())
		}
		this.SendThrough = address
	}
	if jsonConfig.StreamSetting != nil {
		this.StreamSettings = jsonConfig.StreamSetting
	}
	return nil
}
开发者ID:DZLZHCODE,项目名称:v2ray-core,代码行数:26,代码来源:config_json.go


示例4: Save

// Save saves an mbox file from a mbox.Form!
func Save(form *Form) error {
	t := time.Now()
	if form.Email == "@" || form.Email == " " || !strings.ContainsAny(form.Email, "@") || !strings.ContainsAny(form.Email, ".") {
		return errors.New("Blank email address.")
	}
	if ValidationLevel != 1 {
		err := emailx.Validate(form.Email)
		if err != nil {
			if err == emailx.ErrInvalidFormat {
				return errors.New("Email is not valid format.")
			}
			if err == emailx.ErrUnresolvableHost {
				return errors.New("Email is not valid format.")
			}
			return errors.New("Email is not valid format." + err.Error())
		}
	}
	// Normalize email address capitalization
	form.Email = emailx.Normalize(form.Email)
	// mbox files use two different date formats apparently.
	mailtime := t.Format("Mon Jan 2 15:04:05 2006")
	mailtime2 := t.Format("Mon, 2 Jan 2006 15:04:05 -0700")
	Mail.Println("From " + form.Email + " " + mailtime)
	Mail.Println("Return-path: <" + form.Email + ">")
	Mail.Println("Envelope-to: " + Destination)
	Mail.Println("Delivery-date: " + mailtime2)
	Mail.Println("To: " + Destination)
	Mail.Println("Subject: " + form.Subject)
	Mail.Println("From: " + form.Email)
	Mail.Println("Date: " + mailtime2)
	Mail.Println("\n" + form.Message + "\n\n")
	return nil
}
开发者ID:aerth,项目名称:cosgo,代码行数:34,代码来源:mbox.go


示例5: evalStarExpr

func evalStarExpr(ctx *Ctx, starExpr *StarExpr, env *Env) (*reflect.Value, bool, error) {
	// return nil, false, errors.New("Star expressions not done yet")
	var cexpr Expr
	var errs []error
	if cexpr, errs = CheckExpr(ctx, starExpr.X, env); len(errs) != 0 {
		for _, cerr := range errs {
			fmt.Printf("%v\n", cerr)
		}
		return nil, false, errors.New("Something wrong checking * expression")
	}

	xs, _, err := EvalExpr(ctx, cexpr, env)
	if err != nil {
		return nil, false, err
	} else if xs == nil {
		// XXX temporary error until typed evaluation of nil
		return nil, false, errors.New("Cannot dereferece nil type")
	}

	var x reflect.Value
	if x, err = expectSingleValue(ctx, *xs, starExpr.X); err != nil {
		return nil, false, err
	}

	switch x.Type().Kind() {
	case reflect.Interface, reflect.Ptr:
		val := x.Elem()
		return &val, true, nil
	default:
		return nil, true, ErrInvalidIndirect{x.Type()}
	}
}
开发者ID:raff,项目名称:eval,代码行数:32,代码来源:starexpr.go


示例6: Apply

// Apply applies the patch data to the given base.
func Apply(base []byte, patch *common.PatchData, skipCRC bool) ([]byte, error) {
	if uint64(len(base)) != patch.InputFileSize {
		return nil, errors.New("Base file did not have expected size.")
	}
	if !skipCRC && crc32.ChecksumIEEE(base) != patch.InputChecksum {
		return nil, errors.New("Base file did not have expected checksum")
	}

	output := make([]byte, patch.OutputFileSize)
	copy(output, base)

	pointer := 0
	for _, block := range patch.PatchBlocks {
		pointer += int(block.RelativeOffset)

		for _, b := range block.Data {
			if pointer >= len(base) {
				output[pointer] = b
			} else {
				output[pointer] = base[pointer] ^ b
			}
			pointer++
		}

		pointer++
	}

	if !skipCRC && crc32.ChecksumIEEE(output) != patch.OutputChecksum {
		return nil, errors.New("Patch result did not have expected checksum")
	}

	return output, nil
}
开发者ID:rameshvarun,项目名称:ups,代码行数:34,代码来源:apply.go


示例7: validate

func (c *Config) validate() error {
	if c.ID == None {
		return errors.New("cannot use none as id")
	}

	if c.HeartbeatTick <= 0 {
		return errors.New("heartbeat tick must be greater than 0")
	}

	if c.ElectionTick <= c.HeartbeatTick {
		return errors.New("election tick must be greater than heartbeat tick")
	}

	if c.Storage == nil {
		return errors.New("storage cannot be nil")
	}

	if c.MaxInflightMsgs <= 0 {
		return errors.New("max inflight messages must be greater than 0")
	}

	if c.Logger == nil {
		c.Logger = raftLogger
	}

	return nil
}
开发者ID:lebauce,项目名称:skydive,代码行数:27,代码来源:raft.go


示例8: ParseConfigTemplate

// ParseConfigTemplate parses a string into a ConfigTemplate struct
func ParseConfigTemplate(s string) (*ConfigTemplate, error) {
	if len(strings.TrimSpace(s)) < 1 {
		return nil, errors.New("cannot specify empty template declaration")
	}

	var source, destination, command string
	parts := configTemplateRe.FindAllString(s, -1)

	switch len(parts) {
	case 1:
		source = parts[0]
	case 2:
		source, destination = parts[0], parts[1]
	case 3:
		source, destination, command = parts[0], parts[1], parts[2]
	default:
		return nil, errors.New("invalid template declaration format")
	}

	return &ConfigTemplate{
		Source:      source,
		Destination: destination,
		Command:     command,
		Perms:       defaultFilePerms,
	}, nil
}
开发者ID:timopek,项目名称:consul-template,代码行数:27,代码来源:config.go


示例9: GetMember

func GetMember(email, password string) (Member, error) {
	log.Printf("Get member '%s' ('%s')", email, password)
	db, err := GetDBConnection()
	if err == nil {
		defer db.Close()
		pwd := sha256.Sum256([]byte(password))
		log.Printf("Encrypted password: %s", hex.EncodeToString(pwd[:]))
		row := db.QueryRow(`SELECT id, email, first_name
			FROM Member
			WHERE email = $1 AND password = $2`,
			email,
			hex.EncodeToString(pwd[:]),
		)
		result := Member{}
		err = row.Scan(&result.id, &result.email, &result.firstName)
		log.Printf("Err: %v", err)
		if err == nil {
			return result, nil
		} else {
			return result, errors.New("Unable to find Member with email: " + email)
		}
	} else {
		return Member{}, errors.New("Unable to get database connection")
	}
}
开发者ID:Partyschaum,项目名称:go-web-app,代码行数:25,代码来源:member.go


示例10: Load

func (this *User) Load() error {
	db := NewMySQL()

	params := []interface{}{}
	where := ""

	if this.ID > 0 {
		where = "id=?"
		params = append(params, this.ID)
	} else if this.Network != "" && this.UUID != "" {
		where = "network=? AND uuid=?"
		params = append(params, this.Network, this.UUID)
	} else {
		return errors.New("Message missing required fields for load: id or network and uuid")
	}

	result, err := db.Select("SELECT id, network, uuid, name, state, zipcode, created_on, deleted, landing_page, message_window, news, reminders FROM user WHERE "+where+" LIMIT 1", params...)
	if err != nil {
		return err
	}

	for result.Next() {
		err = result.Scan(&this.ID, &this.Network, &this.UUID, &this.Name, &this.State, &this.Zipcode, &this.CreatedOn, &this.Deleted, &this.LandingPage, &this.MessageWindow, &this.News, &this.Reminders)
		if err != nil {
			log.Println(err.Error())
			return err
		}
	}

	if this.CreatedOn == "" || this.Deleted == 1 {
		return errors.New("User not found or deleted.")
	}

	return nil
}
开发者ID:mikeflynn,项目名称:iwillvote,代码行数:35,代码来源:user.go


示例11: ParseRaw

// Extract the username and password from the authorization
// line of an HTTP header. This function will handle the
// parsing and decoding of the line.
func ParseRaw(authLine string) (string, string, error) {
	parts := strings.SplitN(authLine, " ", 2)
	if len(parts) != 2 {
		return "", "", errors.New("Authorization header malformed.")
	}

	method := parts[0]
	if method != "Basic" {
		return "", "", errors.New("Authorization must be basic.")
	}

	payload := parts[1]
	decodedPayload, err := base64.StdEncoding.DecodeString(payload)
	if err != nil {
		return "", "", err
	}

	userPass := strings.SplitN(string(decodedPayload), ":", 2)
	switch len(userPass) {
	case 1:
		return userPass[0], "", nil
	case 2:
		return userPass[0], userPass[1], nil
	}

	return "", "", errors.New("Unable to parse username or password.")
}
开发者ID:Jwpe,项目名称:l2met,代码行数:30,代码来源:auth.go


示例12: CreateSession

func CreateSession(m Member) (Session, error) {
	result := Session{}
	result.memberId = m.Id()
	sessionId := sha256.Sum256([]byte(m.Email() + time.Now().Format("12:00:00")))
	result.sessionId = hex.EncodeToString(sessionId[:])

	db, err := GetDBConnection()
	if err == nil {
		defer db.Close()
		err := db.QueryRow(`INSERT INTO Session
			(member_id, session_id)
			VALUES ($1, $2)
			RETURNING id`,
			m.Id(),
			result.sessionId,
		).Scan(&result.id)
		log.Print(err)
		if err == nil {
			return result, nil
		} else {
			return Session{}, errors.New("Unable to save session to database")
		}
	} else {
		return Session{}, errors.New("Unable to get database connection")
	}
}
开发者ID:Partyschaum,项目名称:go-web-app,代码行数:26,代码来源:member.go


示例13: testAccCheckAWSALBTargetGroupExists

func testAccCheckAWSALBTargetGroupExists(n string, res *elbv2.TargetGroup) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return errors.New("No Target Group ID is set")
		}

		conn := testAccProvider.Meta().(*AWSClient).elbv2conn

		describe, err := conn.DescribeTargetGroups(&elbv2.DescribeTargetGroupsInput{
			TargetGroupArns: []*string{aws.String(rs.Primary.ID)},
		})

		if err != nil {
			return err
		}

		if len(describe.TargetGroups) != 1 ||
			*describe.TargetGroups[0].TargetGroupArn != rs.Primary.ID {
			return errors.New("Target Group not found")
		}

		*res = *describe.TargetGroups[0]
		return nil
	}
}
开发者ID:paultyng,项目名称:terraform,代码行数:30,代码来源:resource_aws_alb_target_group_test.go


示例14: Init

// Init initializes this KeyStore with a password, a path to a folder
// where the keys are stored and a read only flag.
// Each key is stored in a separated file whose name contains the key's SKI
// and flags to identity the key's type.
// If the KeyStore is initialized with a password, this password
// is used to encrypt and decrypt the files storing the keys.
// The pwd can be nil for non-encrypted KeyStores. If an encrypted
// key-store is initialized without a password, then retrieving keys from the
// KeyStore will fail.
// A KeyStore can be read only to avoid the overwriting of keys.
func (ks *FileBasedKeyStore) Init(pwd []byte, path string, readOnly bool) error {
	// Validate inputs
	// pwd can be nil

	if len(path) == 0 {
		return errors.New("An invalid KeyStore path provided. Path cannot be an empty string.")
	}

	ks.m.Lock()
	defer ks.m.Unlock()

	if ks.isOpen {
		return errors.New("KeyStore already initilized.")
	}

	ks.path = path
	ks.pwd = utils.Clone(pwd)

	err := ks.createKeyStoreIfNotExists()
	if err != nil {
		return err
	}

	err = ks.openKeyStore()
	if err != nil {
		return err
	}

	ks.readOnly = readOnly

	return nil
}
开发者ID:hyperledger,项目名称:fabric,代码行数:42,代码来源:fileks.go


示例15: InitHandler

func (h *Host) InitHandler(hl blobserver.FindHandlerByTyper) error {
	_, handler, err := hl.FindHandlerByType("root")
	if err != nil || handler == nil {
		return errors.New("importer requires a 'root' handler")
	}
	rh := handler.(*server.RootHandler)
	searchHandler, ok := rh.SearchHandler()
	if !ok {
		return errors.New("importer requires a 'root' handler with 'searchRoot' defined.")
	}
	h.search = searchHandler
	if rh.Storage == nil {
		return errors.New("importer requires a 'root' handler with 'blobRoot' defined.")
	}
	h.target = rh.Storage

	_, handler, _ = hl.FindHandlerByType("jsonsign")
	if sigh, ok := handler.(*signhandler.Handler); ok {
		h.signer = sigh.Signer()
	}
	if h.signer == nil {
		return errors.New("importer requires a 'jsonsign' handler")
	}

	return nil
}
开发者ID:kdevroede,项目名称:camlistore,代码行数:26,代码来源:importer.go


示例16: rebuildInodePointers

func (inode *DirectoryInode) rebuildInodePointers(fs *FileSystem) error {
	for _, dirent := range inode.EntryList {
		tableInode, ok := fs.InodeTable[dirent.InodeNumber]
		if !ok {
			return errors.New(fmt.Sprintf(
				"%s: no entry in inode table for: %d %p",
				dirent.Name, dirent.InodeNumber, dirent.inode))
		}
		if tableInode == nil {
			return errors.New(fmt.Sprintf(
				"%s: nil entry in inode table for: %d %p",
				dirent.Name, dirent.InodeNumber, dirent.inode))
		} else if dirent.inode != nil && dirent.inode != tableInode {
			return errors.New(fmt.Sprintf(
				"%s: changing inode entry for: %d from: %p to %p\n",
				dirent.Name, dirent.InodeNumber, dirent.inode, tableInode))
		}
		dirent.inode = tableInode
		if inode, ok := dirent.inode.(*DirectoryInode); ok {
			if err := inode.rebuildInodePointers(fs); err != nil {
				return errors.New(dirent.Name + "/" + err.Error())
			}
		}
	}
	return nil
}
开发者ID:datatonic,项目名称:Dominator,代码行数:26,代码来源:rebuild.go


示例17: DownloadByGit

func (n *Node) DownloadByGit(ctx *cli.Context, u *url.URL) error {
	var remoteAddr string
	switch u.Scheme {
	case "git+ssh":
		remoteAddr = fmt.Sprintf("[email protected]%s:%s.git", u.Host, u.Path)
	case "git+http":
		remoteAddr = fmt.Sprintf("http://%s/%s", u.Host, u.Path)
	case "git+https":
		remoteAddr = fmt.Sprintf("https://%s/%s", u.Host, u.Path)
	}
	baseDir := path.Dir(n.InstallPath)
	os.MkdirAll(baseDir, os.ModePerm)
	_, stderr, err := base.ExecCmdDir(baseDir, "git", "clone", remoteAddr, n.InstallPath)
	if err != nil {
		log.Error("Error occurs when 'git clone " + remoteAddr + "'")
		log.Error("\t" + stderr)
		return errors.New(stderr)
	}
	if !n.IsEmptyVal() {
		base.ExecCmdDir(n.InstallPath, "git", "checkout", n.Value)
		if err != nil {
			log.Error("Error occurs when 'git checkout" + n.Value + "'")
			log.Error("\t" + stderr)
			return errors.New(stderr)
		}
	}
	return nil
}
开发者ID:swan-go,项目名称:gopm,代码行数:28,代码来源:struct.go


示例18: GetBoundingOffsets

func (mkc *MockKafkaClient) GetBoundingOffsets(topic string, partition int32) (int64,
	int64, error) {
	topicMap, ok := mkc.messages[topic]
	if !ok {
		return -1, -1, errors.New("No such topic")
	}

	partMap, ok := topicMap[partition]
	if !ok {
		return -1, -1, errors.New("No such partition")
	}

	// because apparently Go is too cool to give native sorting for
	// int64, and the tests will never need offsets > 32 bits
	var offsets []int
	for offset, _ := range partMap {
		offsets = append(offsets, int(offset))
	}

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

	sort.Ints(offsets)
	return int64(offsets[0]), int64(offsets[len(offsets)-1]) + 1, nil
}
开发者ID:carriercomm,项目名称:kafkafs,代码行数:26,代码来源:kafkarofs_test.go


示例19: FindIssuesPointsAndTrophyAction

func FindIssuesPointsAndTrophyAction(payload IssuesPayload) (int, int, error) {
	if payload.Action == nil {
		return 0, 0, errors.New("Cant use empty Action on issues payload.")
	}

	var p int
	var ta int
	switch *payload.Action {
	case "assigned":
		p = points.ASSIGNMENT
		ta = trophies.ASSIGNACTION
	case "unassigned":
		p = points.UNASSIGNMENT
		ta = trophies.ASSIGNACTION
	case "labeled":
		p = points.LABEL
		ta = trophies.LABELACTION
	case "unlabeled":
		p = points.UNLABEL
		ta = trophies.LABELACTION
	case "opened":
		p = points.OPEN_ISSUE
		ta = trophies.ISSUEACTION
	case "closed":
		p = points.CLOSE_ISSUE
		ta = trophies.ISSUEACTION
	case "reopened":
		p = points.REOPEN_ISSUE
		ta = trophies.ISSUEACTION
	default:
		return 0, 0, errors.New("Issue action not known for " + *payload.Action)
	}

	return p, ta, nil
}
开发者ID:tokams,项目名称:autograder,代码行数:35,代码来源:issues.go


示例20: Download

// Download downloads remote package without version control.
func (n *Node) Download(ctx *cli.Context) ([]string, error) {
	for _, s := range services {
		if !strings.HasPrefix(n.DownloadURL, s.prefix) {
			continue
		}

		m := s.pattern.FindStringSubmatch(n.DownloadURL)
		if m == nil {
			if s.prefix != "" {
				return nil, errors.New("Cannot match package service prefix by given path")
			}
			continue
		}

		match := map[string]string{"downloadURL": n.DownloadURL}
		for i, n := range s.pattern.SubexpNames() {
			if n != "" {
				match[n] = m[i]
			}
		}
		return s.get(HttpClient, match, n, ctx)

	}

	if n.ImportPath != n.DownloadURL {
		return nil, errors.New("Didn't find any match service")
	}

	log.Info("Cannot match any service, getting dynamic...")
	return n.getDynamic(HttpClient, ctx)
}
开发者ID:swan-go,项目名称:gopm,代码行数:32,代码来源:struct.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang lex.Lexer类代码示例发布时间:2022-05-24
下一篇:
Golang test.Assert函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap