本文整理汇总了Golang中github.com/pkg/errors.Cause函数的典型用法代码示例。如果您正苦于以下问题:Golang Cause函数的具体用法?Golang Cause怎么用?Golang Cause使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Cause函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
}
示例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)
}
示例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
}
示例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()
}
示例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
}
示例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)
}
示例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
}
示例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
}
示例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)
}
示例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
}
示例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])
}
示例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
}
示例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)
}
示例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
}
示例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)
}