本文整理汇总了Golang中github.com/juju/errgo.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ParseClusterFromFile
// ParseClusterFromFile reads a cluster from file
func ParseClusterFromFile(path string) (*Cluster, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, maskAny(err)
}
// Parse the input
root, err := hcl.Parse(string(data))
if err != nil {
return nil, maskAny(err)
}
// Top-level item should be a list
list, ok := root.Node.(*ast.ObjectList)
if !ok {
return nil, errgo.New("error parsing: root should be an object")
}
matches := list.Filter("cluster")
if len(matches.Items) == 0 {
return nil, errgo.New("'cluster' stanza not found")
}
// Parse hcl into Cluster
cluster := &Cluster{}
if err := cluster.parse(matches); err != nil {
return nil, maskAny(err)
}
cluster.setDefaults()
// Validate the cluster
if err := cluster.validate(); err != nil {
return nil, maskAny(err)
}
return cluster, nil
}
示例2: pageGallery
func pageGallery(w http.ResponseWriter, r *http.Request, p httprouter.Params) *httphelper.HandlerError {
l := httphelper.NewHandlerLogEntry(r)
filepath := path.Join(FlagFolderGallery, p.ByName("path"))
l.Debug("Sending ", filepath)
stat, err := os.Stat(filepath)
if err != nil {
return httphelper.NewHandlerErrorDef(errgo.Notef(err, "can not stat file"))
}
if stat.Mode().IsDir() {
l.Debug("Filetype: Directory")
return pageFilesDirectory(w, r, p)
}
if stat.Mode().IsRegular() {
l.Debug("Filetype: Regular")
return pageFilesRegular(w, r, p)
}
if !stat.Mode().IsDir() && !stat.Mode().IsRegular() {
return httphelper.NewHandlerErrorDef(errgo.New("filetype is not a directory and not a regular file. Something is strange."))
}
return httphelper.NewHandlerErrorDef(errgo.New("unreachable code reached!"))
}
示例3: ParseTodo
func ParseTodo(values []string) (Todo, error) {
if len(values) != 4 {
return Todo{}, errgo.New("entry with the type todo needs exactly four fields")
}
etype, err := ParseEntryType(values[0])
if err != nil {
return Todo{}, errgo.Notef(err, "can not parse entry type")
}
if etype != EntryTypeTodo {
return Todo{}, errgo.New("tried to parse a todo but got the entry type " + etype.String())
}
timestamp, err := time.Parse(TimeStampFormat, values[1])
if err != nil {
return Todo{}, errgo.Notef(err, "can not parse timestamp")
}
active, err := strconv.ParseBool(values[2])
if err != nil {
return Todo{}, errgo.Notef(err, "can not parse active state")
}
return Todo{Active: active, TimeStamp: timestamp, Value: values[3]}, nil
}
示例4: Construct
// Construct sets the necessary options
func (sca *SourceCurrencyAll) Construct(mc config.ModelConstructor) error {
if mc.ConfigReader == nil {
return errgo.New("ConfigReader is required")
}
if mc.Scope == nil {
return errgo.New("Scope is required")
}
sca.mc = mc
return nil
}
示例5: TestCause
func (*errorsSuite) TestCause(c *gc.C) {
c.Assert(errgo.Cause(someErr), gc.Equals, someErr)
causeErr := errgo.New("cause error")
underlyingErr := errgo.New("underlying error") //err TestCause#1
err := errgo.WithCausef(underlyingErr, causeErr, "foo %d", 99) //err TestCause#2
c.Assert(errgo.Cause(err), gc.Equals, causeErr)
checkErr(c, err, underlyingErr, "foo 99: underlying error", "[{$TestCause#2$: foo 99} {$TestCause#1$: underlying error}]", causeErr)
err = &embed{err.(*errgo.Err)}
c.Assert(errgo.Cause(err), gc.Equals, causeErr)
}
示例6: convertValues
func convertValues(store store.Store, project data.ProjectName, values [][]string) error {
for _, value := range values {
if len(value) < 2 {
return errgo.New("value length must be at least 2")
}
timestamp, err := time.Parse(time.RFC3339Nano, value[0])
if err != nil {
return errgo.Notef(err, "can not parse timestamp of value")
}
log.Info("Timestamp: ", timestamp)
switch value[1] {
case "note":
log.Debug("Saving note")
note := data.Note{
Value: value[2],
TimeStamp: timestamp,
}
err := store.AddEntry(project, note)
if err != nil {
return errgo.Notef(err, "can not save note to store")
}
case "todo":
log.Debug("Saving todo")
done, err := strconv.ParseBool(value[3])
if err != nil {
return errgo.Notef(err, "can not parse bool from value")
}
todo := data.Todo{
Value: value[2],
TimeStamp: timestamp,
Active: !done,
}
err = store.AddEntry(project, todo)
if err != nil {
return errgo.Notef(err, "can not save note to store")
}
default:
return errgo.New("do not know what to do with this type of value: " + value[1])
}
}
return nil
}
示例7: TestErrors
func TestErrors(t *testing.T) {
assert.Equal(t, "Err1\nErr2\nErr3", util.Errors(
errors.New("Err1"),
errors.New("Err2"),
errors.New("Err3"),
))
err := util.Errors(
errgo.New("Err1"),
errgo.New("Err2"),
errors.New("Err3"),
)
assert.Contains(t, err, "corestoreio/csfw/util/errors_test.go:34\nErr2")
}
示例8: SetRSA
// SetRSA reads PEM byte data and decodes it and parses the private key.
// Applies the private and the public key to the AuthManager. Password as second
// argument is only required when the private key is encrypted.
// Checks for io.Close and closes the resource. Public key will be derived from
// the private key. Default Signing bits 256.
func SetRSA(privateKey io.Reader, password ...[]byte) OptionFunc {
if cl, ok := privateKey.(io.Closer); ok {
defer func() {
if err := cl.Close(); err != nil { // close file
log.Error("userjwt.RSAKey.ioCloser", "err", err)
}
}()
}
prKeyData, errRA := ioutil.ReadAll(privateKey)
if errRA != nil {
return func(a *AuthManager) {
a.lastError = errgo.Mask(errRA)
}
}
var prKeyPEM *pem.Block
if prKeyPEM, _ = pem.Decode(prKeyData); prKeyPEM == nil {
return func(a *AuthManager) {
a.lastError = errgo.New("Private Key from io.Reader no found")
}
}
var rsaPrivateKey *rsa.PrivateKey
var err error
if x509.IsEncryptedPEMBlock(prKeyPEM) {
if len(password) != 1 || len(password[0]) == 0 {
return func(a *AuthManager) {
a.lastError = errgo.New("Private Key is encrypted but password was not set")
}
}
var dd []byte
var errPEM error
if dd, errPEM = x509.DecryptPEMBlock(prKeyPEM, password[0]); errPEM != nil {
return func(a *AuthManager) {
a.lastError = errgo.Newf("Private Key decryption failed: %s", errPEM.Error())
}
}
rsaPrivateKey, err = x509.ParsePKCS1PrivateKey(dd)
} else {
rsaPrivateKey, err = x509.ParsePKCS1PrivateKey(prKeyPEM.Bytes)
}
return func(a *AuthManager) {
a.SigningMethod = jwt.SigningMethodRS256
a.rsapk = rsaPrivateKey
a.hasKey = true
a.lastError = errgo.Mask(err)
}
}
示例9: Validate
// Validate checks for duplicated configuration paths in all three hierarchy levels.
func (ss SectionSlice) Validate() error {
if len(ss) == 0 {
return errgo.New("SectionSlice is empty")
}
// @todo try to pick the right strategy between maps and slice depending on the overall size of a full SectionSlice
var pc = make(utils.StringSlice, ss.TotalFields()) // pc path checker
i := 0
for _, s := range ss {
for _, g := range s.Groups {
for _, f := range g.Fields {
arg, err := newArg(Path(s.ID, g.ID, f.ID))
if err != nil {
log.Error("config.SectionSlice.Validate.newArg", "err", err, "s", s, "g", g, "f", f)
}
p := arg.scopePath()
if pc.Include(p) {
return errgo.Newf("Duplicate entry for path %s :: %s", p, ss.ToJSON())
}
pc[i] = p
i++
}
}
}
return nil
}
示例10: Setup
func (t *gluonService) Setup(deps service.ServiceDependencies, flags *service.ServiceFlags) error {
if err := flags.SetupDefaults(deps.Logger); err != nil {
return maskAny(err)
}
if flags.Docker.DockerSubnet == "" {
return errgo.New("docker-subnet is missing")
}
changedFlags, err := flags.Save()
if err != nil {
return maskAny(err)
}
changedService, err := createService(deps, flags)
if err != nil {
return maskAny(err)
}
if flags.Force || changedFlags || changedService {
if err := os.Remove(gluonPath); err != nil {
if !os.IsNotExist(err) {
return maskAny(err)
}
}
if err := deps.Systemd.Reload(); err != nil {
return maskAny(err)
}
if err := deps.Systemd.Enable(serviceName); err != nil {
return maskAny(err)
}
}
return nil
}
示例11: TestCause
func TestCause(t *testing.T) {
if cause := errgo.Cause(someErr); cause != someErr {
t.Fatalf("expected %q kind; got %#v", someErr, cause)
}
causeErr := errgo.New("cause error")
underlyingErr := errgo.New("underlying error") //err TestCause#1
err := errgo.WithCausef(underlyingErr, causeErr, "foo %d", 99) //err TestCause#2
if errgo.Cause(err) != causeErr {
t.Fatalf("expected %q; got %#v", causeErr, errgo.Cause(err))
}
checkErr(t, err, underlyingErr, "foo 99: underlying error", "[{$TestCause#2$: foo 99} {$TestCause#1$: underlying error}]", causeErr)
err = &embed{err.(*errgo.Err)}
if errgo.Cause(err) != causeErr {
t.Fatalf("expected %q; got %#v", causeErr, errgo.Cause(err))
}
}
示例12: loadCluster
// loadCluster loads a cluster description from the given flags.
func loadCluster(f *fg.Flags) (*cluster.Cluster, error) {
if f.ClusterPath == "" {
return nil, maskAny(errgo.New("--cluster missing"))
}
clustersPath := os.Getenv("PULCY_CLUSTERS")
if clustersPath == "" {
clustersPath = "config/clusters"
}
path, err := resolvePath(f.ClusterPath, clustersPath, ".hcl")
if err != nil {
return nil, maskAny(err)
}
cluster, err := cluster.ParseClusterFromFile(path)
if err != nil {
return nil, maskAny(err)
}
if f.TunnelOverride != "" {
cluster.Tunnel = f.TunnelOverride
}
if f.Local {
cluster.Tunnel = "core-01"
cluster.Stack = "core-01"
}
return cluster, nil
}
示例13: TestNewErrorFromErrors
func TestNewErrorFromErrors(t *testing.T) {
tests := []struct {
code int
errs []error
wantError string
}{
{http.StatusBadGateway, nil, http.StatusText(http.StatusBadGateway)},
{http.StatusTeapot, []error{errors.New("No coffee pot"), errors.New("Not even a milk pot")}, "No coffee pot\nNot even a milk pot"},
{http.StatusConflict, []error{errgo.New("Now a coffee pot"), errgo.New("Not even close to a milk pot")}, "error_test.go"},
}
for _, test := range tests {
he := ctxhttp.NewErrorFromErrors(test.code, test.errs...)
assert.Exactly(t, test.code, he.Code)
assert.Contains(t, he.Error(), test.wantError)
}
}
示例14: parseJob
// ParseJob takes input from a given reader and parses it into a Job.
func parseJob(input []byte, jf *jobFunctions) (*Job, error) {
// Create a template, add the function map, and parse the text.
tmpl, err := template.New("job").Funcs(jf.Functions()).Parse(string(input))
if err != nil {
return nil, maskAny(err)
}
// Run the template to verify the output.
buffer := &bytes.Buffer{}
err = tmpl.Execute(buffer, jf.Options())
if err != nil {
return nil, maskAny(err)
}
// Parse the input
root, err := hcl.Parse(buffer.String())
if err != nil {
return nil, maskAny(err)
}
// Top-level item should be a list
list, ok := root.Node.(*ast.ObjectList)
if !ok {
return nil, errgo.New("error parsing: root should be an object")
}
// Parse hcl into Job
job := &Job{}
matches := list.Filter("job")
if len(matches.Items) == 0 {
return nil, maskAny(errgo.WithCausef(nil, ValidationError, "'job' stanza not found"))
}
if err := job.parse(matches); err != nil {
return nil, maskAny(err)
}
// Link internal structures
job.prelink()
// Set defaults
job.setDefaults(jf.cluster)
// Replace variables
if err := job.replaceVariables(); err != nil {
return nil, maskAny(err)
}
// Sort internal structures and make final links
job.link()
// Optimize job for cluster
job.optimizeFor(jf.cluster)
// Validate the job
if err := job.Validate(); err != nil {
return nil, maskAny(err)
}
return job, nil
}
示例15: findSwarmType
func findSwarmType(tags []types.Tag) (string, error) {
for _, tag := range tags {
if tag.Key == "StackType" {
return tag.Value, nil
}
}
return "", errgo.New("swarm type not found")
}