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

Golang errors.Cause函数代码示例

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

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



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

示例1: NodeForNodeData

func (p *swarmProvisioner) NodeForNodeData(nodeData provision.NodeStatusData) (provision.Node, error) {
	client, err := chooseDBSwarmNode()
	if err != nil {
		if errors.Cause(err) == errNoSwarmNode {
			return nil, provision.ErrNodeNotFound
		}
	}
	tasks, err := client.ListTasks(docker.ListTasksOptions{})
	if err != nil {
		return nil, err
	}
	var task *swarm.Task
	for _, unitData := range nodeData.Units {
		task, err = findTaskByContainerId(tasks, unitData.ID)
		if err == nil {
			break
		}
		if _, isNotFound := errors.Cause(err).(*provision.UnitNotFoundError); !isNotFound {
			return nil, err
		}
	}
	if task != nil {
		node, err := client.InspectNode(task.NodeID)
		if err != nil {
			if _, notFound := err.(*docker.NoSuchNode); notFound {
				return nil, provision.ErrNodeNotFound
			}
			return nil, err
		}
		return &swarmNodeWrapper{Node: node, provisioner: p}, nil
	}
	return provision.FindNodeByAddrs(p, nodeData.Addrs)
}
开发者ID:tsuru,项目名称:tsuru,代码行数:33,代码来源:provisioner.go


示例2: TestDecryptTLSKeyFalsePositive

// The TLS KEK and the KEK for the headers should be in sync, and so failing
// to decrypt the TLS key should be mean we won't be able to decrypt the headers.
// However, the TLS Key encryption uses AES-256-CBC (golang as of 1.7.x does not seem
// to support GCM, so no cipher modes with digests) so sometimes decrypting with
// the wrong passphrase will not result in an error.  This means we will ultimately
// have to rely on the header encryption mechanism, which does include a digest, to
// determine if the KEK is valid.
func TestDecryptTLSKeyFalsePositive(t *testing.T) {
	badKey := []byte(`
-----BEGIN EC PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,e7927e79e748233776c03c2eb7275f09
kek-version: 392
raft-dek: CAESMBrzZ0gNVPe3FRs42743q8RtkUBrK1ICQpHWX2vdQ8iqSKt1WoKdFDFD2r28LYAVLxoYQguwHbijMx9k+BALUNBAI3s199S5tvnr

JfGenNvzm++AvsOh+UmcBY+JgI6lnfzaCB68agmlmEZYLYi5tqtAU7gif6VIJpCW
+Pj23Fzkw8sKKOOBeapSC5lp+Cjx9OsCci/R9xrdx+uxnnzKJNxOB/qzqcQfZDMh
id2LxdliFcPEk/Yj5gNGpT0UMFJ4G52enbOwOru46f0=
-----END EC PRIVATE KEY-----
`)

	// not actually a real swarm cert - generated a cert corresponding to the key that expires in 20 years
	matchingCert := []byte(`
-----BEGIN CERTIFICATE-----
MIIB9jCCAZygAwIBAgIRAIdzF3Z9VT2OXbRvEw5cR68wCgYIKoZIzj0EAwIwYDEi
MCAGA1UEChMZbWRwMXU5Z3FoOTV1NXN2MmNodDRrcDB1cTEWMBQGA1UECxMNc3dh
cm0tbWFuYWdlcjEiMCAGA1UEAxMZcXJzYmwza2FqOWhiZWprM2R5aWFlc3FiYTAg
GA8wMDAxMDEwMTAwMDAwMFoXDTM2MTEwODA2MjMwMlowYDEiMCAGA1UEChMZbWRw
MXU5Z3FoOTV1NXN2MmNodDRrcDB1cTEWMBQGA1UECxMNc3dhcm0tbWFuYWdlcjEi
MCAGA1UEAxMZcXJzYmwza2FqOWhiZWprM2R5aWFlc3FiYTBZMBMGByqGSM49AgEG
CCqGSM49AwEHA0IABGOivD25E/zcupRFQdKOKbPHS9Mx7JlUhlWnl0iR0K5VhVIU
XjUHt98GuX6gDjs4yUzEKSGxYPsSYlnG9zQqbQSjNTAzMA4GA1UdDwEB/wQEAwIF
oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMAoGCCqGSM49BAMC
A0gAMEUCIQDWtjg1ITGznQILipaEe70G/NgZAOtFfuPXTVkUl3el+wIgSVOVKB/Q
O0T3aXuZGYNyh//KqAoA3erCmh6HauMz84Y=
-----END CERTIFICATE-----
	`)

	var wrongKEK []byte // empty passphrase doesn't decrypt without errors
	falsePositiveKEK, err := base64.RawStdEncoding.DecodeString("bIQgLAAMoGCrHdjMLVhEVqnYTAM7ZNF2xWMiwtw7AiQ")
	require.NoError(t, err)
	realKEK, err := base64.RawStdEncoding.DecodeString("fDg9YejLnMjU+FpulWR62oJLzVpkD2j7VQuP5xiK9QA")
	require.NoError(t, err)

	tempdir, err := ioutil.TempDir("", "KeyReadWriter-false-positive-decryption")
	require.NoError(t, err)
	defer os.RemoveAll(tempdir)

	path := ca.NewConfigPaths(tempdir)
	require.NoError(t, ioutil.WriteFile(path.Node.Key, badKey, 0600))
	require.NoError(t, ioutil.WriteFile(path.Node.Cert, matchingCert, 0644))

	krw := ca.NewKeyReadWriter(path.Node, wrongKEK, RaftDEKData{})
	_, _, err = krw.Read()
	require.IsType(t, ca.ErrInvalidKEK{}, errors.Cause(err))

	krw = ca.NewKeyReadWriter(path.Node, falsePositiveKEK, RaftDEKData{})
	_, _, err = krw.Read()
	require.Error(t, err)
	require.IsType(t, ca.ErrInvalidKEK{}, errors.Cause(err))

	krw = ca.NewKeyReadWriter(path.Node, realKEK, RaftDEKData{})
	_, _, err = krw.Read()
	require.NoError(t, err)
}
开发者ID:docker,项目名称:swarmkit,代码行数:65,代码来源:deks_test.go


示例3: isErr

func isErr(err error, expected error) bool {
	err = errors.Cause(err)
	switch pe := err.(type) {
	case nil:
		return false
	case *OpErr:
		err = errors.Cause(pe.Err)
	}
	return err == expected
}
开发者ID:justincormack,项目名称:docker,代码行数:10,代码来源:errors.go


示例4: printErr

func printErr(name string, err error) {
	fmt.Printf("== %s ==\n", name)
	fmt.Printf("Message: %v\n", err)
	fmt.Printf("Type: %T\n", err)
	fmt.Printf("Original error? %v\n", errors.Cause(err))
	fmt.Printf("Original type? %T\n", errors.Cause(err))
	printStack(err)

	fmt.Println()
}
开发者ID:gowroc,项目名称:meetups,代码行数:10,代码来源:main.go


示例5: ErrorToJSONAPIError

// ErrorToJSONAPIError returns the JSONAPI representation
// of an error and the HTTP status code that will be associated with it.
// This function knows about the models package and the errors from there
// as well as goa error classes.
func ErrorToJSONAPIError(err error) (app.JSONAPIError, int) {
	cause := errs.Cause(err)
	detail := cause.Error()
	var title, code string
	var statusCode int
	var id *string
	switch cause.(type) {
	case errors.NotFoundError:
		code = ErrorCodeNotFound
		title = "Not found error"
		statusCode = http.StatusNotFound
	case errors.ConversionError:
		code = ErrorCodeConversionError
		title = "Conversion error"
		statusCode = http.StatusBadRequest
	case errors.BadParameterError:
		code = ErrorCodeBadParameter
		title = "Bad parameter error"
		statusCode = http.StatusBadRequest
	case errors.VersionConflictError:
		code = ErrorCodeVersionConflict
		title = "Version conflict error"
		statusCode = http.StatusBadRequest
	case errors.InternalError:
		code = ErrorCodeInternalError
		title = "Internal error"
		statusCode = http.StatusInternalServerError
	default:
		code = ErrorCodeUnknownError
		title = "Unknown error"
		statusCode = http.StatusInternalServerError

		cause := errs.Cause(err)
		if err, ok := cause.(goa.ServiceError); ok {
			statusCode = err.ResponseStatus()
			idStr := err.Token()
			id = &idStr
			title = http.StatusText(statusCode)
		}
		if errResp, ok := cause.(*goa.ErrorResponse); ok {
			code = errResp.Code
			detail = errResp.Detail
		}
	}
	statusCodeStr := strconv.Itoa(statusCode)
	jerr := app.JSONAPIError{
		ID:     id,
		Code:   &code,
		Status: &statusCodeStr,
		Title:  &title,
		Detail: detail,
	}
	return jerr, statusCode
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:58,代码来源:jsonapi_utility.go


示例6: main

func main() {
	fmt.Println("Hello world!")
	err := getError()
	err = errors.Wrap(err, "open failed")
	err = subErr(err)
	err = errors.Wrap(err, "read config failed")

	pp.Println("Cause: ", errors.Cause(err))
	err = errors.Wrap(err, "New message")
	pp.Println("Error: ", err)
	fmt.Printf("[%+v]\n", err)
	fmt.Printf("{%+v}\n", errors.Cause(err))
	fmt.Printf("[%v]\n", err)
}
开发者ID:plumbum,项目名称:go-samples,代码行数:14,代码来源:main.go


示例7: New

// New creates a new Cluster instance using provided config.
func New(config Config) (*Cluster, error) {
	root := filepath.Join(config.Root, swarmDirName)
	if err := os.MkdirAll(root, 0700); err != nil {
		return nil, err
	}
	if config.RuntimeRoot == "" {
		config.RuntimeRoot = root
	}
	if err := os.MkdirAll(config.RuntimeRoot, 0700); err != nil {
		return nil, err
	}
	c := &Cluster{
		root:        root,
		config:      config,
		configEvent: make(chan struct{}, 10),
		runtimeRoot: config.RuntimeRoot,
		attachers:   make(map[string]*attacher),
	}

	nodeConfig, err := c.loadState()
	if err != nil {
		if os.IsNotExist(err) {
			return c, nil
		}
		return nil, err
	}

	n, err := c.startNewNode(*nodeConfig)
	if err != nil {
		return nil, err
	}

	select {
	case <-time.After(swarmConnectTimeout):
		logrus.Error("swarm component could not be started before timeout was reached")
	case <-n.Ready():
	case <-n.done:
		if errors.Cause(c.err) == ErrSwarmLocked {
			return c, nil
		}
		if err, ok := errors.Cause(c.err).(x509.CertificateInvalidError); ok && err.Reason == x509.Expired {
			c.err = ErrSwarmCertificatesExpired
			return c, nil
		}
		return nil, fmt.Errorf("swarm component could not be started: %v", c.err)
	}
	go c.reconnectOnFailure(n)
	return c, nil
}
开发者ID:djs55,项目名称:docker,代码行数:50,代码来源:cluster.go


示例8: New

// New creates a new Cluster instance using provided config.
func New(config Config) (*Cluster, error) {
	root := filepath.Join(config.Root, swarmDirName)
	if err := os.MkdirAll(root, 0700); err != nil {
		return nil, err
	}
	if config.RuntimeRoot == "" {
		config.RuntimeRoot = root
	}
	if err := os.MkdirAll(config.RuntimeRoot, 0700); err != nil {
		return nil, err
	}
	c := &Cluster{
		root:        root,
		config:      config,
		configEvent: make(chan struct{}, 10),
		runtimeRoot: config.RuntimeRoot,
		attachers:   make(map[string]*attacher),
	}

	nodeConfig, err := loadPersistentState(root)
	if err != nil {
		if os.IsNotExist(err) {
			return c, nil
		}
		return nil, err
	}

	nr, err := c.newNodeRunner(*nodeConfig)
	if err != nil {
		return nil, err
	}
	c.nr = nr

	select {
	case <-time.After(swarmConnectTimeout):
		logrus.Error("swarm component could not be started before timeout was reached")
	case err := <-nr.Ready():
		if err != nil {
			if errors.Cause(err) == errSwarmLocked {
				return c, nil
			}
			if err, ok := errors.Cause(c.nr.err).(x509.CertificateInvalidError); ok && err.Reason == x509.Expired {
				return c, nil
			}
			return nil, errors.Wrap(err, "swarm component could not be started")
		}
	}
	return c, nil
}
开发者ID:shakamunyi,项目名称:docker,代码行数:50,代码来源:cluster.go


示例9: TestCreateToolhelp32Snapshot

func TestCreateToolhelp32Snapshot(t *testing.T) {
	handle, err := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
	if err != nil {
		t.Fatal(err)
	}
	defer syscall.CloseHandle(syscall.Handle(handle))

	// Iterate over the snapshots until our PID is found.
	pid := uint32(syscall.Getpid())
	for {
		process, err := Process32Next(handle)
		if errors.Cause(err) == syscall.ERROR_NO_MORE_FILES {
			break
		}
		if err != nil {
			t.Fatal(err)
		}

		t.Logf("CreateToolhelp32Snapshot: ProcessEntry32=%v", process)

		if process.ProcessID == pid {
			assert.EqualValues(t, syscall.Getppid(), process.ParentProcessID)
			return
		}
	}

	assert.Fail(t, "Snapshot not found for PID=%v", pid)
}
开发者ID:elastic,项目名称:gosigar,代码行数:28,代码来源:syscall_windows_test.go


示例10: dbAddNamesForID

func (nc *NameCache) dbAddNamesForID(id int64, ins []string) error {
	add, err := nc.DB.Prepare("insert or replace into docker_search_name " +
		"(metadata_id, name) values ($1, $2)")
	if err != nil {
		return errors.Wrap(err, "adding names")
	}

	for _, n := range ins {
		_, err := add.Exec(id, n)
		if err != nil {
			Log.Vomit.Printf("%v %T", errors.Cause(err), errors.Cause(err))
			return errors.Wrapf(err, "adding name: %s", n)
		}
	}
	return nil
}
开发者ID:opentable,项目名称:sous,代码行数:16,代码来源:image_mapping.go


示例11: ensureInDB

func (nc *NameCache) ensureInDB(sel, ins string, args ...interface{}) (id int64, err error) {
	selN := len(sqlBindingRE.FindAllString(sel, -1))
	insN := len(sqlBindingRE.FindAllString(ins, -1))
	if selN > len(args) {
		return 0, errors.Errorf("only %d args when %d needed for %q", len(args), selN, sel)
	}
	if insN > len(args) {
		return 0, errors.Errorf("only %d args when %d needed for %q", len(args), insN, ins)
	}

	row := nc.DB.QueryRow(sel, args[0:selN]...)
	err = row.Scan(&id)
	if err == nil {
		Log.Vomit.Printf("Found id: %d with %q %v", id, sel, args)
		return
	}

	if errors.Cause(err) != sql.ErrNoRows {
		return 0, errors.Wrapf(err, "getting id with %q %v", sel, args[0:selN])
	}

	nr, err := nc.DB.Exec(ins, args[0:insN]...)
	if err != nil {
		return 0, errors.Wrapf(err, "inserting new value: %q %v", ins, args[0:insN])
	}
	id, err = nr.LastInsertId()
	Log.Vomit.Printf("Made (?err: %v) id: %d with %q", err, id, ins)
	return id, errors.Wrapf(err, "getting id of new value: %q %v", ins, args[0:insN])
}
开发者ID:opentable,项目名称:sous,代码行数:29,代码来源:image_mapping.go


示例12: Run

func (f decodeJSONFields) Run(event common.MapStr) (common.MapStr, error) {
	var errs []string

	for _, field := range f.fields {
		data, err := event.GetValue(field)
		if err != nil && errors.Cause(err) != common.ErrKeyNotFound {
			debug("Error trying to GetValue for field : %s in event : %v", field, event)
			errs = append(errs, err.Error())
			continue
		}
		text, ok := data.(string)
		if ok {
			var output interface{}
			err := unmarshal(f.maxDepth, []byte(text), &output, f.processArray)
			if err != nil {
				debug("Error trying to unmarshal %s", event[field])
				errs = append(errs, err.Error())
				continue
			}

			_, err = event.Put(field, output)
			if err != nil {
				debug("Error trying to Put value %v for field : %s", output, field)
				errs = append(errs, err.Error())
				continue
			}
		}
	}

	if len(errs) > 0 {
		return event, fmt.Errorf(strings.Join(errs, ", "))
	}
	return event, nil
}
开发者ID:ruflin,项目名称:beats,代码行数:34,代码来源:decode_json_fields.go


示例13: TestCreateLoadWITWithList

func (s *workItemTypeRepoBlackBoxTest) TestCreateLoadWITWithList() {
	bt := "string"
	wit, err := s.repo.Create(context.Background(), nil, "foo_bar", map[string]app.FieldDefinition{
		"foo": {
			Required: true,
			Type: &app.FieldType{
				ComponentType: &bt,
				Kind:          string(workitem.KindList),
			},
		},
	})
	assert.Nil(s.T(), err)
	assert.NotNil(s.T(), wit)

	wit3, err := s.repo.Create(context.Background(), nil, "foo_bar", map[string]app.FieldDefinition{})
	assert.IsType(s.T(), errors.BadParameterError{}, errs.Cause(err))
	assert.Nil(s.T(), wit3)

	wit2, err := s.repo.Load(context.Background(), "foo_bar")
	assert.Nil(s.T(), err)
	require.NotNil(s.T(), wit2)
	field := wit2.Fields["foo"]
	require.NotNil(s.T(), field)
	assert.Equal(s.T(), string(workitem.KindList), field.Type.Kind)
	assert.Equal(s.T(), true, field.Required)
	assert.Nil(s.T(), field.Type.BaseType)
	assert.Nil(s.T(), field.Type.Values)
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:28,代码来源:workitemtype_repository_blackbox_test.go


示例14: needCommit

func (gsm *GitStateManager) needCommit() bool {
	err := gsm.git("diff-index", "--exit-code", "HEAD")
	if ee, is := errors.Cause(err).(*exec.ExitError); is {
		return !ee.Success()
	}
	return false
}
开发者ID:opentable,项目名称:sous,代码行数:7,代码来源:git_state_manager.go


示例15: PopulateTokenEndpointResponse

func (c *OpenIDConnectExplicitHandler) PopulateTokenEndpointResponse(ctx context.Context, req *http.Request, requester fosite.AccessRequester, responder fosite.AccessResponder) error {
	if !requester.GetGrantTypes().Exact("authorization_code") {
		return errors.Wrap(fosite.ErrUnknownRequest, "")
	}

	authorize, err := c.OpenIDConnectRequestStorage.GetOpenIDConnectSession(ctx, requester.GetRequestForm().Get("code"), requester)
	if errors.Cause(err) == ErrNoSessionFound {
		return errors.Wrap(fosite.ErrUnknownRequest, err.Error())
	} else if err != nil {
		return errors.Wrap(fosite.ErrServerError, err.Error())
	}

	if !authorize.GetGrantedScopes().Has("openid") {
		return errors.Wrap(fosite.ErrMisconfiguration, "The an openid connect session was found but the openid scope is missing in it")
	}

	if !requester.GetClient().GetGrantTypes().Has("authorization_code") {
		return errors.Wrap(fosite.ErrInvalidGrant, "The client is not allowed to use the authorization_code grant type")
	}

	if !requester.GetClient().GetResponseTypes().Has("id_token") {
		return errors.Wrap(fosite.ErrInvalidGrant, "The client is not allowed to use response type id_token")
	}

	return c.IssueExplicitIDToken(ctx, req, authorize, responder)
}
开发者ID:cristiangraz,项目名称:fosite,代码行数:26,代码来源:flow_explicit_token.go


示例16: Get

// Get returns an enabled plugin matching the given name and capability.
func (ps *Store) Get(name, capability string, mode int) (plugingetter.CompatPlugin, error) {
	var (
		p   *v2.Plugin
		err error
	)

	// Lookup using new model.
	if ps != nil {
		p, err = ps.GetV2Plugin(name)
		if err == nil {
			p.AddRefCount(mode)
			if p.IsEnabled() {
				return p.FilterByCap(capability)
			}
			// Plugin was found but it is disabled, so we should not fall back to legacy plugins
			// but we should error out right away
			return nil, ErrNotFound(name)
		}
		if _, ok := errors.Cause(err).(ErrNotFound); !ok {
			return nil, err
		}
	}

	// Lookup using legacy model.
	if allowV1PluginsFallback {
		p, err := plugins.Get(name, capability)
		if err != nil {
			return nil, fmt.Errorf("legacy plugin: %v", err)
		}
		return p, nil
	}

	return nil, err
}
开发者ID:docker,项目名称:docker,代码行数:35,代码来源:store.go


示例17: BuildGRPCError

// BuildGRPCError returns the error with a GRPC code
func BuildGRPCError(err error) error {
	if err == nil {
		return nil
	}
	code := grpc.Code(err)
	if code != codes.Unknown {
		return err // it already is a gRPC error
	}
	switch errs.Cause(err).(type) {
	case *ErrAlreadyExists:
		code = codes.AlreadyExists
	case *ErrInternal:
		code = codes.Internal
	case *ErrInvalidArgument:
		code = codes.InvalidArgument
	case *ErrNotFound:
		code = codes.NotFound
	case *ErrPermissionDenied:
		code = codes.PermissionDenied
	}
	switch err {
	case context.Canceled:
		code = codes.Canceled
	case io.EOF:
		code = codes.OutOfRange
	}
	return grpc.Errorf(code, err.Error())
}
开发者ID:TheThingsNetwork,项目名称:ttn,代码行数:29,代码来源:errors.go


示例18: createWorkItemLink

func createWorkItemLink(ctx *workItemLinkContext, funcs createWorkItemLinkFuncs, payload *app.CreateWorkItemLinkPayload) error {
	// Convert payload from app to model representation
	model := link.WorkItemLink{}
	in := app.WorkItemLinkSingle{
		Data: payload.Data,
	}
	err := link.ConvertLinkToModel(in, &model)
	if err != nil {
		jerrors, _ := jsonapi.ErrorToJSONAPIErrors(err)
		return funcs.BadRequest(jerrors)
	}
	link, err := ctx.Application.WorkItemLinks().Create(ctx.Context, model.SourceID, model.TargetID, model.LinkTypeID)
	if err != nil {
		cause := errs.Cause(err)
		switch cause.(type) {
		case errors.NotFoundError:
			jerrors, _ := jsonapi.ErrorToJSONAPIErrors(goa.ErrBadRequest(err.Error()))
			return funcs.BadRequest(jerrors)
		case errors.BadParameterError:
			jerrors, _ := jsonapi.ErrorToJSONAPIErrors(goa.ErrBadRequest(err.Error()))
			return funcs.BadRequest(jerrors)
		default:
			jerrors, httpStatusCode := jsonapi.ErrorToJSONAPIErrors(err)
			return ctx.ResponseData.Service.Send(ctx.Context, httpStatusCode, jerrors)
		}
	}
	if err := enrichLinkSingle(ctx, link); err != nil {
		jerrors, httpStatusCode := jsonapi.ErrorToJSONAPIErrors(err)
		return ctx.ResponseData.Service.Send(ctx.Context, httpStatusCode, jerrors)
	}

	ctx.ResponseData.Header().Set("Location", app.WorkItemLinkHref(link.Data.ID))
	return funcs.Created(link)
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:34,代码来源:work-item-link.go


示例19: maybeDecorateGRPCError

func maybeDecorateGRPCError(wrapped cmdFn) cmdFn {
	return func(cmd *cobra.Command, args []string) error {
		err := wrapped(cmd, args)

		{
			unwrappedErr := errors.Cause(err)
			if unwrappedErr == nil {
				return err
			}
			_, isSendError := unwrappedErr.(*roachpb.SendError)
			isGRPCError := grpcutil.IsClosedConnection(unwrappedErr)
			_, isNetError := unwrappedErr.(*net.OpError)
			if !(isSendError || isGRPCError || isNetError) {
				return err // intentionally return original to keep wrapping
			}
		}

		format := `unable to connect or connection lost.

Please check the address and credentials such as certificates (if attempting to
communicate with a secure cluster).

%s`

		return errors.Errorf(format, err)
	}
}
开发者ID:knz,项目名称:cockroach,代码行数:27,代码来源:error.go


示例20: ShouldRetry

// ShouldRetry looks at an error and tries to work out if retrying the
// operation that caused it would be a good idea. It returns true if
// the error implements Timeout() or Temporary() or if the error
// indicates a premature closing of the connection.
func ShouldRetry(err error) bool {
	if err == nil {
		return false
	}

	// Find root cause if available
	err = errors.Cause(err)

	// Unwrap url.Error
	if urlErr, ok := err.(*url.Error); ok {
		err = urlErr.Err
	}

	// Look for premature closing of connection
	if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) {
		return true
	}

	// Check for net error Timeout()
	if x, ok := err.(interface {
		Timeout() bool
	}); ok && x.Timeout() {
		return true
	}

	// Check for net error Temporary()
	if x, ok := err.(interface {
		Temporary() bool
	}); ok && x.Temporary() {
		return true
	}

	return false
}
开发者ID:ncw,项目名称:rclone,代码行数:38,代码来源:error.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang errors.Errorf函数代码示例发布时间:2022-05-28
下一篇:
Golang browser.OpenURL函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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