refactor(errors): rename pkglib/error to lib/errors

Signed-off-by: He Weiwei <hweiwei@vmware.com>
This commit is contained in:
He Weiwei 2020-03-28 05:04:16 +00:00
parent 98759642b7
commit 9c06c79ff4
73 changed files with 407 additions and 336 deletions

View File

@ -17,7 +17,7 @@ package artifact
import ( import (
"container/list" "container/list"
"context" "context"
"errors" stderrors "errors"
"fmt" "fmt"
"strings" "strings"
"time" "time"
@ -34,7 +34,7 @@ import (
"github.com/goharbor/harbor/src/controller/event/metadata" "github.com/goharbor/harbor/src/controller/event/metadata"
"github.com/goharbor/harbor/src/controller/tag" "github.com/goharbor/harbor/src/controller/tag"
"github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"github.com/goharbor/harbor/src/pkg/artifact" "github.com/goharbor/harbor/src/pkg/artifact"
@ -59,10 +59,10 @@ var (
var ( var (
// ErrBreak error to break walk // ErrBreak error to break walk
ErrBreak = errors.New("break") ErrBreak = stderrors.New("break")
// ErrSkip error to skip walk the children of the artifact // ErrSkip error to skip walk the children of the artifact
ErrSkip = errors.New("skip") ErrSkip = stderrors.New("skip")
) )
// Controller defines the operations related with artifacts and tags // Controller defines the operations related with artifacts and tags
@ -164,7 +164,7 @@ func (c *controller) ensureArtifact(ctx context.Context, repository, digest stri
} }
// got other error when get the artifact, return the error // got other error when get the artifact, return the error
if !ierror.IsErr(err, ierror.NotFoundCode) { if !errors.IsErr(err, errors.NotFoundCode) {
return false, nil, err return false, nil, err
} }
@ -196,7 +196,7 @@ func (c *controller) ensureArtifact(ctx context.Context, repository, digest stri
id, err := c.artMgr.Create(ctx, artifact) id, err := c.artMgr.Create(ctx, artifact)
if err != nil { if err != nil {
// if got conflict error, try to get the artifact again // if got conflict error, try to get the artifact again
if ierror.IsConflictErr(err) { if errors.IsConflictErr(err) {
var e error var e error
artifact, e = c.artMgr.GetByDigest(ctx, repository, digest) artifact, e = c.artMgr.GetByDigest(ctx, repository, digest)
if e != nil { if e != nil {
@ -208,7 +208,7 @@ func (c *controller) ensureArtifact(ctx context.Context, repository, digest stri
created = true created = true
artifact.ID = id artifact.ID = id
return nil return nil
})(ctx); err != nil && !ierror.IsConflictErr(err) { })(ctx); err != nil && !errors.IsConflictErr(err) {
return false, nil, err return false, nil, err
} }
@ -272,7 +272,7 @@ func (c *controller) getByTag(ctx context.Context, repository, tag string, optio
return nil, err return nil, err
} }
if len(tags) == 0 { if len(tags) == 0 {
return nil, ierror.New(nil).WithCode(ierror.NotFoundCode). return nil, errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("artifact %s:%s not found", repository, tag) WithMessage("artifact %s:%s not found", repository, tag)
} }
return c.Get(ctx, tags[0].ArtifactID, option) return c.Get(ctx, tags[0].ArtifactID, option)
@ -288,7 +288,7 @@ func (c *controller) deleteDeeply(ctx context.Context, id int64, isRoot bool) er
art, err := c.Get(ctx, id, &Option{WithTag: true}) art, err := c.Get(ctx, id, &Option{WithTag: true})
if err != nil { if err != nil {
// return nil if the nonexistent artifact isn't the root parent // return nil if the nonexistent artifact isn't the root parent
if !isRoot && ierror.IsErr(err, ierror.NotFoundCode) { if !isRoot && errors.IsErr(err, errors.NotFoundCode) {
return nil return nil
} }
return err return err
@ -309,7 +309,7 @@ func (c *controller) deleteDeeply(ctx context.Context, id int64, isRoot bool) er
if len(parents) > 0 { if len(parents) > 0 {
// the root artifact is referenced by other artifacts // the root artifact is referenced by other artifacts
if isRoot { if isRoot {
return ierror.New(nil).WithCode(ierror.ViolateForeignKeyConstraintCode). return errors.New(nil).WithCode(errors.ViolateForeignKeyConstraintCode).
WithMessage("the deleting artifact is referenced by others") WithMessage("the deleting artifact is referenced by others")
} }
// the child artifact is referenced by other artifacts, skip // the child artifact is referenced by other artifacts, skip
@ -319,7 +319,7 @@ func (c *controller) deleteDeeply(ctx context.Context, id int64, isRoot bool) er
for _, reference := range art.References { for _, reference := range art.References {
// delete reference // delete reference
if err = c.artMgr.DeleteReference(ctx, reference.ID); err != nil && if err = c.artMgr.DeleteReference(ctx, reference.ID); err != nil &&
!ierror.IsErr(err, ierror.NotFoundCode) { !errors.IsErr(err, errors.NotFoundCode) {
return err return err
} }
if err = c.deleteDeeply(ctx, reference.ChildID, false); err != nil { if err = c.deleteDeeply(ctx, reference.ChildID, false); err != nil {
@ -346,7 +346,7 @@ func (c *controller) deleteDeeply(ctx context.Context, id int64, isRoot bool) er
// delete the artifact itself // delete the artifact itself
if err = c.artMgr.Delete(ctx, art.ID); err != nil { if err = c.artMgr.Delete(ctx, art.ID); err != nil {
// the child artifact doesn't exist, skip // the child artifact doesn't exist, skip
if !isRoot && ierror.IsErr(err, ierror.NotFoundCode) { if !isRoot && errors.IsErr(err, errors.NotFoundCode) {
return nil return nil
} }
return err return err
@ -372,7 +372,7 @@ func (c *controller) deleteDeeply(ctx context.Context, id int64, isRoot bool) er
Digest: art.Digest, Digest: art.Digest,
}) })
return err return err
})(ctx); err != nil && !ierror.IsErr(err, ierror.ConflictCode) { })(ctx); err != nil && !errors.IsErr(err, errors.ConflictCode) {
return err return err
} }
@ -419,13 +419,13 @@ func (c *controller) copyDeeply(ctx context.Context, srcRepo, reference, dstRepo
if err == nil { if err == nil {
// return conflict error if the root parent artifact already exists under the destination repository // return conflict error if the root parent artifact already exists under the destination repository
if isRoot { if isRoot {
return 0, ierror.New(nil).WithCode(ierror.ConflictCode). return 0, errors.New(nil).WithCode(errors.ConflictCode).
WithMessage("the artifact %s@%s already exists", dstRepo, digest) WithMessage("the artifact %s@%s already exists", dstRepo, digest)
} }
// the child artifact already under the destination repository, skip // the child artifact already under the destination repository, skip
return dstArt.ID, nil return dstArt.ID, nil
} }
if !ierror.IsErr(err, ierror.NotFoundCode) { if !errors.IsErr(err, errors.NotFoundCode) {
return 0, err return 0, err
} }

View File

@ -22,7 +22,7 @@ import (
"github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/models"
"github.com/goharbor/harbor/src/controller/tag" "github.com/goharbor/harbor/src/controller/tag"
"github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"github.com/goharbor/harbor/src/pkg/artifact" "github.com/goharbor/harbor/src/pkg/artifact"
@ -148,7 +148,7 @@ func (c *controllerTestSuite) TestEnsureArtifact() {
c.repoMgr.On("GetByName").Return(&models.RepoRecord{ c.repoMgr.On("GetByName").Return(&models.RepoRecord{
ProjectID: 1, ProjectID: 1,
}, nil) }, nil)
c.artMgr.On("GetByDigest").Return(nil, ierror.NotFoundError(nil)) c.artMgr.On("GetByDigest").Return(nil, errors.NotFoundError(nil))
c.artMgr.On("Create").Return(1, nil) c.artMgr.On("Create").Return(1, nil)
c.abstractor.On("AbstractMetadata").Return(nil) c.abstractor.On("AbstractMetadata").Return(nil)
created, art, err = c.ctl.ensureArtifact(orm.NewContext(nil, &ormtesting.FakeOrmer{}), "library/hello-world", digest) created, art, err = c.ctl.ensureArtifact(orm.NewContext(nil, &ormtesting.FakeOrmer{}), "library/hello-world", digest)
@ -164,7 +164,7 @@ func (c *controllerTestSuite) TestEnsure() {
c.repoMgr.On("GetByName").Return(&models.RepoRecord{ c.repoMgr.On("GetByName").Return(&models.RepoRecord{
ProjectID: 1, ProjectID: 1,
}, nil) }, nil)
c.artMgr.On("GetByDigest").Return(nil, ierror.NotFoundError(nil)) c.artMgr.On("GetByDigest").Return(nil, errors.NotFoundError(nil))
c.artMgr.On("Create").Return(1, nil) c.artMgr.On("Create").Return(1, nil)
c.abstractor.On("AbstractMetadata").Return(nil) c.abstractor.On("AbstractMetadata").Return(nil)
c.tagCtl.On("Ensure").Return(nil) c.tagCtl.On("Ensure").Return(nil)
@ -236,11 +236,11 @@ func (c *controllerTestSuite) TestGetByDigest() {
c.repoMgr.On("GetByName").Return(&models.RepoRecord{ c.repoMgr.On("GetByName").Return(&models.RepoRecord{
RepositoryID: 1, RepositoryID: 1,
}, nil) }, nil)
c.artMgr.On("GetByDigest").Return(nil, ierror.NotFoundError(nil)) c.artMgr.On("GetByDigest").Return(nil, errors.NotFoundError(nil))
art, err := c.ctl.getByDigest(nil, "library/hello-world", art, err := c.ctl.getByDigest(nil, "library/hello-world",
"sha256:418fb88ec412e340cdbef913b8ca1bbe8f9e8dc705f9617414c1f2c8db980180", nil) "sha256:418fb88ec412e340cdbef913b8ca1bbe8f9e8dc705f9617414c1f2c8db980180", nil)
c.Require().NotNil(err) c.Require().NotNil(err)
c.True(ierror.IsErr(err, ierror.NotFoundCode)) c.True(errors.IsErr(err, errors.NotFoundCode))
// reset the mock // reset the mock
c.SetupTest() c.SetupTest()
@ -269,7 +269,7 @@ func (c *controllerTestSuite) TestGetByTag() {
c.tagCtl.On("List").Return(nil, nil) c.tagCtl.On("List").Return(nil, nil)
art, err := c.ctl.getByTag(nil, "library/hello-world", "latest", nil) art, err := c.ctl.getByTag(nil, "library/hello-world", "latest", nil)
c.Require().NotNil(err) c.Require().NotNil(err)
c.True(ierror.IsErr(err, ierror.NotFoundCode)) c.True(errors.IsErr(err, errors.NotFoundCode))
// reset the mock // reset the mock
c.SetupTest() c.SetupTest()
@ -343,16 +343,16 @@ func (c *controllerTestSuite) TestGetByReference() {
func (c *controllerTestSuite) TestDeleteDeeply() { func (c *controllerTestSuite) TestDeleteDeeply() {
// root artifact and doesn't exist // root artifact and doesn't exist
c.artMgr.On("Get").Return(nil, ierror.NotFoundError(nil)) c.artMgr.On("Get").Return(nil, errors.NotFoundError(nil))
err := c.ctl.deleteDeeply(orm.NewContext(nil, &ormtesting.FakeOrmer{}), 1, true) err := c.ctl.deleteDeeply(orm.NewContext(nil, &ormtesting.FakeOrmer{}), 1, true)
c.Require().NotNil(err) c.Require().NotNil(err)
c.Assert().True(ierror.IsErr(err, ierror.NotFoundCode)) c.Assert().True(errors.IsErr(err, errors.NotFoundCode))
// reset the mock // reset the mock
c.SetupTest() c.SetupTest()
// child artifact and doesn't exist // child artifact and doesn't exist
c.artMgr.On("Get").Return(nil, ierror.NotFoundError(nil)) c.artMgr.On("Get").Return(nil, errors.NotFoundError(nil))
err = c.ctl.deleteDeeply(orm.NewContext(nil, &ormtesting.FakeOrmer{}), 1, false) err = c.ctl.deleteDeeply(orm.NewContext(nil, &ormtesting.FakeOrmer{}), 1, false)
c.Require().Nil(err) c.Require().Nil(err)
@ -414,7 +414,7 @@ func (c *controllerTestSuite) TestCopy() {
RepositoryID: 1, RepositoryID: 1,
Name: "library/hello-world", Name: "library/hello-world",
}, nil) }, nil)
c.artMgr.On("GetByDigest").Return(nil, ierror.NotFoundError(nil)) c.artMgr.On("GetByDigest").Return(nil, errors.NotFoundError(nil))
c.tagCtl.On("List").Return([]*tag.Tag{ c.tagCtl.On("List").Return([]*tag.Tag{
{ {
Tag: model_tag.Tag{ Tag: model_tag.Tag{

View File

@ -17,7 +17,7 @@ package base
import ( import (
"context" "context"
"github.com/goharbor/harbor/src/controller/artifact/processor" "github.com/goharbor/harbor/src/controller/artifact/processor"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/artifact" "github.com/goharbor/harbor/src/pkg/artifact"
"github.com/goharbor/harbor/src/pkg/registry" "github.com/goharbor/harbor/src/pkg/registry"
) )
@ -42,7 +42,7 @@ func (m *IndexProcessor) AbstractMetadata(ctx context.Context, content []byte, a
// AbstractAddition abstracts the addition of artifact // AbstractAddition abstracts the addition of artifact
func (m *IndexProcessor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*processor.Addition, error) { func (m *IndexProcessor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*processor.Addition, error) {
return nil, ierror.New(nil).WithCode(ierror.BadRequestCode). return nil, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("addition %s isn't supported", addition) WithMessage("addition %s isn't supported", addition)
} }

View File

@ -18,7 +18,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"github.com/goharbor/harbor/src/controller/artifact/processor" "github.com/goharbor/harbor/src/controller/artifact/processor"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/artifact" "github.com/goharbor/harbor/src/pkg/artifact"
"github.com/goharbor/harbor/src/pkg/registry" "github.com/goharbor/harbor/src/pkg/registry"
"github.com/opencontainers/image-spec/specs-go/v1" "github.com/opencontainers/image-spec/specs-go/v1"
@ -74,7 +74,7 @@ func (m *ManifestProcessor) AbstractMetadata(ctx context.Context, content []byte
// AbstractAddition abstracts the addition of artifact // AbstractAddition abstracts the addition of artifact
func (m *ManifestProcessor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*processor.Addition, error) { func (m *ManifestProcessor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*processor.Addition, error) {
return nil, ierror.New(nil).WithCode(ierror.BadRequestCode). return nil, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("addition %s isn't supported", addition) WithMessage("addition %s isn't supported", addition)
} }

View File

@ -22,7 +22,7 @@ import (
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
ps "github.com/goharbor/harbor/src/controller/artifact/processor" ps "github.com/goharbor/harbor/src/controller/artifact/processor"
"github.com/goharbor/harbor/src/controller/artifact/processor/base" "github.com/goharbor/harbor/src/controller/artifact/processor/base"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/artifact" "github.com/goharbor/harbor/src/pkg/artifact"
"github.com/goharbor/harbor/src/pkg/chart" "github.com/goharbor/harbor/src/pkg/chart"
v1 "github.com/opencontainers/image-spec/specs-go/v1" v1 "github.com/opencontainers/image-spec/specs-go/v1"
@ -59,7 +59,7 @@ type processor struct {
func (p *processor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*ps.Addition, error) { func (p *processor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*ps.Addition, error) {
if addition != AdditionTypeValues && addition != AdditionTypeReadme && addition != AdditionTypeDependencies { if addition != AdditionTypeValues && addition != AdditionTypeReadme && addition != AdditionTypeDependencies {
return nil, ierror.New(nil).WithCode(ierror.BadRequestCode). return nil, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("addition %s isn't supported for %s", addition, ArtifactTypeChart) WithMessage("addition %s isn't supported for %s", addition, ArtifactTypeChart)
} }

View File

@ -17,7 +17,7 @@ package chart
import ( import (
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/goharbor/harbor/src/controller/artifact/processor/base" "github.com/goharbor/harbor/src/controller/artifact/processor/base"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/artifact" "github.com/goharbor/harbor/src/pkg/artifact"
chartserver "github.com/goharbor/harbor/src/pkg/chart" chartserver "github.com/goharbor/harbor/src/pkg/chart"
"github.com/goharbor/harbor/src/testing/pkg/chart" "github.com/goharbor/harbor/src/testing/pkg/chart"
@ -49,7 +49,7 @@ func (p *processorTestSuite) SetupTest() {
func (p *processorTestSuite) TestAbstractAddition() { func (p *processorTestSuite) TestAbstractAddition() {
// unknown addition // unknown addition
_, err := p.processor.AbstractAddition(nil, nil, "unknown_addition") _, err := p.processor.AbstractAddition(nil, nil, "unknown_addition")
p.True(ierror.IsErr(err, ierror.BadRequestCode)) p.True(errors.IsErr(err, errors.BadRequestCode))
chartManifest := `{"schemaVersion":2,"config":{"mediaType":"application/vnd.cncf.helm.config.v1+json","digest":"sha256:76a59ebef39013bf7b57e411629b569a5175590024f31eeaaa577a0f8da9e523","size":528},"layers":[{"mediaType":"application/tar+gzip","digest":"sha256:0bd64cfb958b68c71b46597e22185a41e784dc96e04090bc7d2a480b704c3b65","size":12607}]}` chartManifest := `{"schemaVersion":2,"config":{"mediaType":"application/vnd.cncf.helm.config.v1+json","digest":"sha256:76a59ebef39013bf7b57e411629b569a5175590024f31eeaaa577a0f8da9e523","size":528},"layers":[{"mediaType":"application/tar+gzip","digest":"sha256:0bd64cfb958b68c71b46597e22185a41e784dc96e04090bc7d2a480b704c3b65","size":12607}]}`

View File

@ -16,7 +16,7 @@ package processor
import ( import (
"context" "context"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/artifact" "github.com/goharbor/harbor/src/pkg/artifact"
"regexp" "regexp"
"strings" "strings"
@ -54,6 +54,6 @@ func (d *defaultProcessor) AbstractMetadata(ctx context.Context, manifest []byte
} }
func (d *defaultProcessor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*Addition, error) { func (d *defaultProcessor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*Addition, error) {
// return error directly // return error directly
return nil, ierror.New(nil).WithCode(ierror.BadRequestCode). return nil, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("the processor for artifact %s not found, cannot get the addition", artifact.Type) WithMessage("the processor for artifact %s not found, cannot get the addition", artifact.Type)
} }

View File

@ -20,7 +20,7 @@ import (
"github.com/docker/distribution/manifest/schema1" "github.com/docker/distribution/manifest/schema1"
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/controller/artifact/processor" "github.com/goharbor/harbor/src/controller/artifact/processor"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/artifact" "github.com/goharbor/harbor/src/pkg/artifact"
) )
@ -49,7 +49,7 @@ func (m *manifestV1Processor) AbstractMetadata(ctx context.Context, manifest []b
} }
func (m *manifestV1Processor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*processor.Addition, error) { func (m *manifestV1Processor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*processor.Addition, error) {
return nil, ierror.New(nil).WithCode(ierror.BadRequestCode). return nil, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("addition %s isn't supported for %s(manifest version 1)", addition, ArtifactTypeImage) WithMessage("addition %s isn't supported for %s(manifest version 1)", addition, ArtifactTypeImage)
} }

View File

@ -15,7 +15,7 @@
package image package image
import ( import (
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/artifact" "github.com/goharbor/harbor/src/pkg/artifact"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"testing" "testing"
@ -85,7 +85,7 @@ func (m *manifestV1ProcessorTestSuite) TestAbstractMetadata() {
func (m *manifestV1ProcessorTestSuite) TestAbstractAddition() { func (m *manifestV1ProcessorTestSuite) TestAbstractAddition() {
_, err := m.processor.AbstractAddition(nil, nil, AdditionTypeBuildHistory) _, err := m.processor.AbstractAddition(nil, nil, AdditionTypeBuildHistory)
m.True(ierror.IsErr(err, ierror.BadRequestCode)) m.True(errors.IsErr(err, errors.BadRequestCode))
} }
func (m *manifestV1ProcessorTestSuite) TestGetArtifactType() { func (m *manifestV1ProcessorTestSuite) TestGetArtifactType() {

View File

@ -21,7 +21,7 @@ import (
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/controller/artifact/processor" "github.com/goharbor/harbor/src/controller/artifact/processor"
"github.com/goharbor/harbor/src/controller/artifact/processor/base" "github.com/goharbor/harbor/src/controller/artifact/processor/base"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/artifact" "github.com/goharbor/harbor/src/pkg/artifact"
"github.com/opencontainers/image-spec/specs-go/v1" "github.com/opencontainers/image-spec/specs-go/v1"
) )
@ -53,7 +53,7 @@ type manifestV2Processor struct {
func (m *manifestV2Processor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*processor.Addition, error) { func (m *manifestV2Processor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*processor.Addition, error) {
if addition != AdditionTypeBuildHistory { if addition != AdditionTypeBuildHistory {
return nil, ierror.New(nil).WithCode(ierror.BadRequestCode). return nil, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("addition %s isn't supported for %s(manifest version 2)", addition, ArtifactTypeImage) WithMessage("addition %s isn't supported for %s(manifest version 2)", addition, ArtifactTypeImage)
} }
mani, _, err := m.RegCli.PullManifest(artifact.RepositoryName, artifact.Digest) mani, _, err := m.RegCli.PullManifest(artifact.RepositoryName, artifact.Digest)

View File

@ -18,7 +18,7 @@ import (
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/manifest/schema2" "github.com/docker/distribution/manifest/schema2"
"github.com/goharbor/harbor/src/controller/artifact/processor/base" "github.com/goharbor/harbor/src/controller/artifact/processor/base"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/artifact" "github.com/goharbor/harbor/src/pkg/artifact"
"github.com/goharbor/harbor/src/testing/pkg/registry" "github.com/goharbor/harbor/src/testing/pkg/registry"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
@ -138,7 +138,7 @@ func (m *manifestV2ProcessorTestSuite) SetupTest() {
func (m *manifestV2ProcessorTestSuite) TestAbstractAddition() { func (m *manifestV2ProcessorTestSuite) TestAbstractAddition() {
// unknown addition // unknown addition
_, err := m.processor.AbstractAddition(nil, nil, "unknown_addition") _, err := m.processor.AbstractAddition(nil, nil, "unknown_addition")
m.True(ierror.IsErr(err, ierror.BadRequestCode)) m.True(errors.IsErr(err, errors.BadRequestCode))
// build history // build history
artifact := &artifact.Artifact{} artifact := &artifact.Artifact{}

View File

@ -23,7 +23,7 @@ import (
"github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/models"
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
util "github.com/goharbor/harbor/src/common/utils/redis" util "github.com/goharbor/harbor/src/common/utils/redis"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/pkg/blob" "github.com/goharbor/harbor/src/pkg/blob"
) )
@ -134,7 +134,7 @@ func (c *controller) Ensure(ctx context.Context, digest string, contentType stri
return blob.ID, nil return blob.ID, nil
} }
if !ierror.IsNotFoundErr(err) { if !errors.IsNotFoundErr(err) {
return 0, err return 0, err
} }
@ -143,12 +143,12 @@ func (c *controller) Ensure(ctx context.Context, digest string, contentType stri
func (c *controller) Exist(ctx context.Context, digest string, options ...Option) (bool, error) { func (c *controller) Exist(ctx context.Context, digest string, options ...Option) (bool, error) {
if digest == "" { if digest == "" {
return false, ierror.BadRequestError(nil).WithMessage("exist blob require digest") return false, errors.BadRequestError(nil).WithMessage("exist blob require digest")
} }
_, err := c.Get(ctx, digest, options...) _, err := c.Get(ctx, digest, options...)
if err != nil { if err != nil {
if ierror.IsNotFoundErr(err) { if errors.IsNotFoundErr(err) {
return false, nil return false, nil
} }
@ -196,7 +196,7 @@ func (c *controller) FindMissingAssociationsForProject(ctx context.Context, proj
func (c *controller) Get(ctx context.Context, digest string, options ...Option) (*blob.Blob, error) { func (c *controller) Get(ctx context.Context, digest string, options ...Option) (*blob.Blob, error) {
if digest == "" { if digest == "" {
return nil, ierror.New(nil).WithCode(ierror.BadRequestCode).WithMessage("require digest") return nil, errors.New(nil).WithCode(errors.BadRequestCode).WithMessage("require digest")
} }
opts := newOptions(options...) opts := newOptions(options...)
@ -211,7 +211,7 @@ func (c *controller) Get(ctx context.Context, digest string, options ...Option)
if err != nil { if err != nil {
return nil, err return nil, err
} else if len(blobs) == 0 { } else if len(blobs) == 0 {
return nil, ierror.NotFoundError(nil).WithMessage("blob %s not found", digest) return nil, errors.NotFoundError(nil).WithMessage("blob %s not found", digest)
} }
return blobs[0], nil return blobs[0], nil

View File

@ -20,7 +20,7 @@ import (
"github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/models"
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/core/promgr/metamgr" "github.com/goharbor/harbor/src/core/promgr/metamgr"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/project" "github.com/goharbor/harbor/src/pkg/project"
"github.com/goharbor/harbor/src/pkg/scan/whitelist" "github.com/goharbor/harbor/src/pkg/scan/whitelist"
) )
@ -61,7 +61,7 @@ func (c *controller) Get(ctx context.Context, projectID int64, options ...Option
return nil, err return nil, err
} }
if p == nil { if p == nil {
return nil, ierror.NotFoundError(nil).WithMessage("project %d not found", projectID) return nil, errors.NotFoundError(nil).WithMessage("project %d not found", projectID)
} }
return c.assembleProject(ctx, p, newOptions(options...)) return c.assembleProject(ctx, p, newOptions(options...))
@ -69,7 +69,7 @@ func (c *controller) Get(ctx context.Context, projectID int64, options ...Option
func (c *controller) GetByName(ctx context.Context, projectName string, options ...Option) (*models.Project, error) { func (c *controller) GetByName(ctx context.Context, projectName string, options ...Option) (*models.Project, error) {
if projectName == "" { if projectName == "" {
return nil, ierror.BadRequestError(nil).WithMessage("project name required") return nil, errors.BadRequestError(nil).WithMessage("project name required")
} }
p, err := c.projectMgr.Get(projectName) p, err := c.projectMgr.Get(projectName)
@ -77,7 +77,7 @@ func (c *controller) GetByName(ctx context.Context, projectName string, options
return nil, err return nil, err
} }
if p == nil { if p == nil {
return nil, ierror.NotFoundError(nil).WithMessage("project %s not found", projectName) return nil, errors.NotFoundError(nil).WithMessage("project %s not found", projectName)
} }
return c.assembleProject(ctx, p, newOptions(options...)) return c.assembleProject(ctx, p, newOptions(options...))

View File

@ -20,7 +20,7 @@ import (
"testing" "testing"
"github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/models"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/testing/pkg/project" "github.com/goharbor/harbor/src/testing/pkg/project"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
) )
@ -47,14 +47,14 @@ func (suite *ControllerTestSuite) TestGetByName() {
{ {
p, err := c.GetByName(context.TODO(), "test", Metadata(false)) p, err := c.GetByName(context.TODO(), "test", Metadata(false))
suite.Error(err) suite.Error(err)
suite.True(ierror.IsNotFoundErr(err)) suite.True(errors.IsNotFoundErr(err))
suite.Nil(p) suite.Nil(p)
} }
{ {
p, err := c.GetByName(context.TODO(), "oops", Metadata(false)) p, err := c.GetByName(context.TODO(), "oops", Metadata(false))
suite.Error(err) suite.Error(err)
suite.False(ierror.IsNotFoundErr(err)) suite.False(errors.IsNotFoundErr(err))
suite.Nil(p) suite.Nil(p)
} }
} }

View File

@ -22,7 +22,7 @@ import (
"github.com/garyburd/redigo/redis" "github.com/garyburd/redigo/redis"
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
util "github.com/goharbor/harbor/src/common/utils/redis" util "github.com/goharbor/harbor/src/common/utils/redis"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/pkg/quota" "github.com/goharbor/harbor/src/pkg/quota"
"github.com/goharbor/harbor/src/pkg/quota/driver" "github.com/goharbor/harbor/src/pkg/quota/driver"
@ -168,7 +168,7 @@ func (c *controller) reserveResources(ctx context.Context, reference, referenceI
newReserved := types.Add(reserved, resources) newReserved := types.Add(reserved, resources)
if err := quota.IsSafe(hardLimits, types.Add(used, reserved), types.Add(used, newReserved), false); err != nil { if err := quota.IsSafe(hardLimits, types.Add(used, reserved), types.Add(used, newReserved), false); err != nil {
return ierror.DeniedError(err).WithMessage("Quota exceeded when processing the request of %v", err) return errors.DeniedError(err).WithMessage("Quota exceeded when processing the request of %v", err)
} }
if err := c.setReservedResources(ctx, reference, referenceID, newReserved); err != nil { if err := c.setReservedResources(ctx, reference, referenceID, newReserved); err != nil {

View File

@ -20,7 +20,7 @@ import (
"github.com/goharbor/harbor/src/common/dao" "github.com/goharbor/harbor/src/common/dao"
"github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/models"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/project" "github.com/goharbor/harbor/src/pkg/project"
"github.com/graph-gophers/dataloader" "github.com/graph-gophers/dataloader"
) )
@ -70,7 +70,7 @@ func getProjectsBatchFn(ctx context.Context, keys dataloader.Keys) []*dataloader
for _, projectID := range projectIDs { for _, projectID := range projectIDs {
project, ok := projectsMap[projectID] project, ok := projectsMap[projectID]
if !ok { if !ok {
err := ierror.NotFoundError(nil).WithMessage("project %d not found", projectID) err := errors.NotFoundError(nil).WithMessage("project %d not found", projectID)
return handleError(err) return handleError(err)
} }

View File

@ -22,7 +22,7 @@ import (
"github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/models"
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/controller/project" "github.com/goharbor/harbor/src/controller/project"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
) )
const ( const (
@ -92,7 +92,7 @@ func RefreshForProjects(ctx context.Context) error {
referenceID := ReferenceID(p.ProjectID) referenceID := ReferenceID(p.ProjectID)
_, err := Ctl.GetByRef(ctx, ProjectReference, referenceID) _, err := Ctl.GetByRef(ctx, ProjectReference, referenceID)
if ierror.IsNotFoundErr(err) { if errors.IsNotFoundErr(err) {
if _, err := Ctl.Create(ctx, ProjectReference, referenceID, driver.HardLimits(ctx)); err != nil { if _, err := Ctl.Create(ctx, ProjectReference, referenceID, driver.HardLimits(ctx)); err != nil {
log.Warningf("initialize quota for project %s failed, error: %v", p.Name, err) log.Warningf("initialize quota for project %s failed, error: %v", p.Name, err)
continue continue

View File

@ -21,7 +21,7 @@ import (
"github.com/goharbor/harbor/src/common/utils" "github.com/goharbor/harbor/src/common/utils"
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/controller/artifact" "github.com/goharbor/harbor/src/controller/artifact"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
art "github.com/goharbor/harbor/src/pkg/artifact" art "github.com/goharbor/harbor/src/pkg/artifact"
@ -81,7 +81,7 @@ func (c *controller) Ensure(ctx context.Context, name string) (bool, int64, erro
} }
// got other error when get the repository, return the error // got other error when get the repository, return the error
if !ierror.IsErr(err, ierror.NotFoundCode) { if !errors.IsErr(err, errors.NotFoundCode) {
return false, 0, err return false, 0, err
} }
@ -105,7 +105,7 @@ func (c *controller) Ensure(ctx context.Context, name string) (bool, int64, erro
}) })
if err != nil { if err != nil {
// if got conflict error, try to get again // if got conflict error, try to get again
if ierror.IsConflictErr(err) { if errors.IsConflictErr(err) {
var e error var e error
repository, e = c.repoMgr.GetByName(ctx, name) repository, e = c.repoMgr.GetByName(ctx, name)
if e != nil { if e != nil {
@ -118,7 +118,7 @@ func (c *controller) Ensure(ctx context.Context, name string) (bool, int64, erro
} }
created = true created = true
return nil return nil
})(ctx); err != nil && !ierror.IsConflictErr(err) { })(ctx); err != nil && !errors.IsConflictErr(err) {
return false, 0, err return false, 0, err
} }

View File

@ -17,7 +17,7 @@ package repository
import ( import (
"github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/models"
"github.com/goharbor/harbor/src/controller/artifact" "github.com/goharbor/harbor/src/controller/artifact"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
artifacttesting "github.com/goharbor/harbor/src/testing/controller/artifact" artifacttesting "github.com/goharbor/harbor/src/testing/controller/artifact"
ormtesting "github.com/goharbor/harbor/src/testing/lib/orm" ormtesting "github.com/goharbor/harbor/src/testing/lib/orm"
@ -68,7 +68,7 @@ func (c *controllerTestSuite) TestEnsure() {
c.SetupTest() c.SetupTest()
// doesn't exist // doesn't exist
c.repoMgr.On("GetByName").Return(nil, ierror.NotFoundError(nil)) c.repoMgr.On("GetByName").Return(nil, errors.NotFoundError(nil))
c.proMgr.On("Get", "library").Return(&models.Project{ c.proMgr.On("Get", "library").Return(&models.Project{
ProjectID: 1, ProjectID: 1,
}, nil) }, nil)

View File

@ -29,7 +29,7 @@ import (
"github.com/goharbor/harbor/src/core/config" "github.com/goharbor/harbor/src/core/config"
"github.com/goharbor/harbor/src/jobservice/job" "github.com/goharbor/harbor/src/jobservice/job"
"github.com/goharbor/harbor/src/jobservice/logger" "github.com/goharbor/harbor/src/jobservice/logger"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/permission/types" "github.com/goharbor/harbor/src/pkg/permission/types"
"github.com/goharbor/harbor/src/pkg/robot" "github.com/goharbor/harbor/src/pkg/robot"
"github.com/goharbor/harbor/src/pkg/robot/model" "github.com/goharbor/harbor/src/pkg/robot/model"
@ -41,7 +41,6 @@ import (
"github.com/goharbor/harbor/src/pkg/scan/report" "github.com/goharbor/harbor/src/pkg/scan/report"
v1 "github.com/goharbor/harbor/src/pkg/scan/rest/v1" v1 "github.com/goharbor/harbor/src/pkg/scan/rest/v1"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/pkg/errors"
) )
// DefaultController is a default singleton scan API controller. // DefaultController is a default singleton scan API controller.
@ -197,7 +196,7 @@ func (bc *basicController) Scan(ctx context.Context, artifact *ar.Artifact, opti
for _, art := range artifacts { for _, art := range artifacts {
trackID, producesMimes, err := bc.makeReportPlaceholder(ctx, r, art, options...) trackID, producesMimes, err := bc.makeReportPlaceholder(ctx, r, art, options...)
if err != nil { if err != nil {
if ierror.IsConflictErr(err) { if errors.IsConflictErr(err) {
errs = append(errs, err) errs = append(errs, err)
} else { } else {
return err return err
@ -324,7 +323,7 @@ func (bc *basicController) GetReport(ctx context.Context, artifact *ar.Artifact,
} }
if r == nil { if r == nil {
return nil, ierror.NotFoundError(nil).WithMessage("no scanner registration configured for project: %d", artifact.ProjectID) return nil, errors.NotFoundError(nil).WithMessage("no scanner registration configured for project: %d", artifact.ProjectID)
} }
artifacts, scannable, err := bc.collectScanningArtifacts(ctx, r, artifact) artifacts, scannable, err := bc.collectScanningArtifacts(ctx, r, artifact)
@ -333,7 +332,7 @@ func (bc *basicController) GetReport(ctx context.Context, artifact *ar.Artifact,
} }
if !scannable { if !scannable {
return nil, ierror.NotFoundError(nil).WithMessage("report not found for %s@%s", artifact.RepositoryName, artifact.Digest) return nil, errors.NotFoundError(nil).WithMessage("report not found for %s@%s", artifact.RepositoryName, artifact.Digest)
} }
groupReports := make([][]*scan.Report, len(artifacts)) groupReports := make([][]*scan.Report, len(artifacts))

View File

@ -1,10 +1,24 @@
// Copyright Project Harbor Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tag package tag
import ( import (
"context" "context"
"github.com/goharbor/harbor/src/common/utils" "github.com/goharbor/harbor/src/common/utils"
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"github.com/goharbor/harbor/src/lib/selector" "github.com/goharbor/harbor/src/lib/selector"
@ -80,7 +94,7 @@ func (c *controller) Ensure(ctx context.Context, repositoryID, artifactID int64,
} }
// existing tag must check the immutable status and signature // existing tag must check the immutable status and signature
if tag.Immutable { if tag.Immutable {
return ierror.New(nil).WithCode(ierror.PreconditionCode). return errors.New(nil).WithCode(errors.PreconditionCode).
WithMessage("the tag %s configured as immutable, cannot be updated", tag.Name) WithMessage("the tag %s configured as immutable, cannot be updated", tag.Name)
} }
// the tag exists under the repository, but it is attached to other artifact // the tag exists under the repository, but it is attached to other artifact
@ -101,7 +115,7 @@ func (c *controller) Ensure(ctx context.Context, repositoryID, artifactID int64,
tag.PushTime = time.Now() tag.PushTime = time.Now()
_, err = c.Create(ctx, tag) _, err = c.Create(ctx, tag)
return err return err
})(ctx); err != nil && !ierror.IsConflictErr(err) { })(ctx); err != nil && !errors.IsConflictErr(err) {
return err return err
} }
@ -163,11 +177,11 @@ func (c *controller) Delete(ctx context.Context, id int64) (err error) {
return err return err
} }
if tag.Immutable { if tag.Immutable {
return ierror.New(nil).WithCode(ierror.PreconditionCode). return errors.New(nil).WithCode(errors.PreconditionCode).
WithMessage("the tag %s configured as immutable, cannot be deleted", tag.Name) WithMessage("the tag %s configured as immutable, cannot be deleted", tag.Name)
} }
if tag.Signed { if tag.Signed {
return ierror.New(nil).WithCode(ierror.PreconditionCode). return errors.New(nil).WithCode(errors.PreconditionCode).
WithMessage("the tag %s with signature cannot be deleted", tag.Name) WithMessage("the tag %s with signature cannot be deleted", tag.Name)
} }
return c.tagMgr.Delete(ctx, id) return c.tagMgr.Delete(ctx, id)

View File

@ -1,9 +1,23 @@
// Copyright Project Harbor Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tag package tag
import ( import (
"github.com/goharbor/harbor/src/common" "github.com/goharbor/harbor/src/common"
coreConfig "github.com/goharbor/harbor/src/core/config" coreConfig "github.com/goharbor/harbor/src/core/config"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
pkg_artifact "github.com/goharbor/harbor/src/pkg/artifact" pkg_artifact "github.com/goharbor/harbor/src/pkg/artifact"
"github.com/goharbor/harbor/src/pkg/tag/model/tag" "github.com/goharbor/harbor/src/pkg/tag/model/tag"
@ -157,7 +171,7 @@ func (c *controllerTestSuite) TestDeleteImmutable() {
c.tagMgr.On("Delete").Return(nil) c.tagMgr.On("Delete").Return(nil)
err := c.ctl.Delete(nil, 1) err := c.ctl.Delete(nil, 1)
c.Require().NotNil(err) c.Require().NotNil(err)
c.True(ierror.IsErr(err, ierror.PreconditionCode)) c.True(errors.IsErr(err, errors.PreconditionCode))
} }
func (c *controllerTestSuite) TestUpdate() { func (c *controllerTestSuite) TestUpdate() {

View File

@ -16,7 +16,6 @@ package api
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"net/http" "net/http"
@ -29,7 +28,7 @@ import (
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/core/config" "github.com/goharbor/harbor/src/core/config"
"github.com/goharbor/harbor/src/core/promgr" "github.com/goharbor/harbor/src/core/promgr"
internal_errors "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/project" "github.com/goharbor/harbor/src/pkg/project"
"github.com/goharbor/harbor/src/pkg/repository" "github.com/goharbor/harbor/src/pkg/repository"
"github.com/goharbor/harbor/src/pkg/retention" "github.com/goharbor/harbor/src/pkg/retention"
@ -50,10 +49,6 @@ var (
retentionController retention.APIController retentionController retention.APIController
) )
var (
errNotFound = errors.New("not found")
)
// BaseController ... // BaseController ...
type BaseController struct { type BaseController struct {
api.BaseAPI api.BaseAPI
@ -81,7 +76,7 @@ func (b *BaseController) Prepare() {
// otherwise send Unauthorized response and returns false // otherwise send Unauthorized response and returns false
func (b *BaseController) RequireAuthenticated() bool { func (b *BaseController) RequireAuthenticated() bool {
if !b.SecurityCtx.IsAuthenticated() { if !b.SecurityCtx.IsAuthenticated() {
b.SendError(internal_errors.UnauthorizedError(errors.New("Unauthorized"))) b.SendError(errors.UnauthorizedError(errors.New("Unauthorized")))
return false return false
} }
return true return true
@ -100,7 +95,7 @@ func (b *BaseController) HasProjectPermission(projectIDOrName interface{}, actio
return false, err return false, err
} }
if project == nil { if project == nil {
return false, errNotFound return false, errors.NotFoundError(nil).WithMessage("project %s not found", projectName)
} }
projectID = project.ProjectID projectID = project.ProjectID
@ -119,20 +114,16 @@ func (b *BaseController) HasProjectPermission(projectIDOrName interface{}, actio
func (b *BaseController) RequireProjectAccess(projectIDOrName interface{}, action rbac.Action, subresource ...rbac.Resource) bool { func (b *BaseController) RequireProjectAccess(projectIDOrName interface{}, action rbac.Action, subresource ...rbac.Resource) bool {
hasPermission, err := b.HasProjectPermission(projectIDOrName, action, subresource...) hasPermission, err := b.HasProjectPermission(projectIDOrName, action, subresource...)
if err != nil { if err != nil {
if errors.Is(err, errNotFound) { b.SendError(err)
b.SendError(internal_errors.New(errors.New(b.SecurityCtx.GetUsername())).WithCode(internal_errors.NotFoundCode))
} else {
b.SendError(err)
}
return false return false
} }
if !hasPermission { if !hasPermission {
if !b.SecurityCtx.IsAuthenticated() { if !b.SecurityCtx.IsAuthenticated() {
b.SendError(internal_errors.UnauthorizedError(errors.New("Unauthorized"))) b.SendError(errors.UnauthorizedError(errors.New("Unauthorized")))
} else { } else {
b.SendError(internal_errors.New(errors.New(b.SecurityCtx.GetUsername())).WithCode(internal_errors.ForbiddenCode)) b.SendError(errors.New(errors.New(b.SecurityCtx.GetUsername())).WithCode(errors.ForbiddenCode))
} }
return false return false

View File

@ -1,3 +1,17 @@
// Copyright Project Harbor Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api package api
import ( import (
@ -7,7 +21,7 @@ import (
"strings" "strings"
"github.com/goharbor/harbor/src/common/rbac" "github.com/goharbor/harbor/src/common/rbac"
internal_errors "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/immutabletag" "github.com/goharbor/harbor/src/pkg/immutabletag"
"github.com/goharbor/harbor/src/pkg/immutabletag/model" "github.com/goharbor/harbor/src/pkg/immutabletag/model"
) )
@ -36,7 +50,7 @@ func (itr *ImmutableTagRuleAPI) Prepare() {
} else { } else {
text += fmt.Sprintf("%d", pid) text += fmt.Sprintf("%d", pid)
} }
itr.SendError(internal_errors.New(err).WithCode(internal_errors.BadRequestCode)) itr.SendError(errors.New(err).WithCode(errors.BadRequestCode))
return return
} }
itr.projectID = pid itr.projectID = pid
@ -51,7 +65,7 @@ func (itr *ImmutableTagRuleAPI) Prepare() {
} }
if itRule.ProjectID != itr.projectID { if itRule.ProjectID != itr.projectID {
err := fmt.Errorf("immutable tag rule %v not found", itr.ID) err := fmt.Errorf("immutable tag rule %v not found", itr.ID)
itr.SendError(internal_errors.New(err).WithCode(internal_errors.NotFoundCode)) itr.SendError(errors.New(err).WithCode(errors.NotFoundCode))
return return
} }
} }
@ -95,7 +109,7 @@ func (itr *ImmutableTagRuleAPI) Post() {
ir := &model.Metadata{} ir := &model.Metadata{}
isValid, err := itr.DecodeJSONReqAndValidate(ir) isValid, err := itr.DecodeJSONReqAndValidate(ir)
if !isValid { if !isValid {
itr.SendError(internal_errors.New(err).WithCode(internal_errors.BadRequestCode)) itr.SendError(errors.New(err).WithCode(errors.BadRequestCode))
return return
} }
ir.ProjectID = itr.projectID ir.ProjectID = itr.projectID
@ -111,7 +125,7 @@ func (itr *ImmutableTagRuleAPI) Post() {
func (itr *ImmutableTagRuleAPI) Delete() { func (itr *ImmutableTagRuleAPI) Delete() {
if itr.ID <= 0 { if itr.ID <= 0 {
err := fmt.Errorf("invalid immutable rule id %d", itr.ID) err := fmt.Errorf("invalid immutable rule id %d", itr.ID)
itr.SendError(internal_errors.New(err).WithCode(internal_errors.BadRequestCode)) itr.SendError(errors.New(err).WithCode(errors.BadRequestCode))
return return
} }
err := itr.ctr.DeleteImmutableRule(itr.ID) err := itr.ctr.DeleteImmutableRule(itr.ID)
@ -125,7 +139,7 @@ func (itr *ImmutableTagRuleAPI) Delete() {
func (itr *ImmutableTagRuleAPI) Put() { func (itr *ImmutableTagRuleAPI) Put() {
ir := &model.Metadata{} ir := &model.Metadata{}
if err := itr.DecodeJSONReq(ir); err != nil { if err := itr.DecodeJSONReq(ir); err != nil {
itr.SendError(internal_errors.New(err).WithCode(internal_errors.BadRequestCode)) itr.SendError(errors.New(err).WithCode(errors.BadRequestCode))
return return
} }
ir.ID = itr.ID ir.ID = itr.ID
@ -133,7 +147,7 @@ func (itr *ImmutableTagRuleAPI) Put() {
if itr.ID <= 0 { if itr.ID <= 0 {
err := fmt.Errorf("invalid immutable rule id %d", itr.ID) err := fmt.Errorf("invalid immutable rule id %d", itr.ID)
itr.SendError(internal_errors.New(err).WithCode(internal_errors.BadRequestCode)) itr.SendError(errors.New(err).WithCode(errors.BadRequestCode))
return return
} }

View File

@ -24,9 +24,8 @@ import (
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/controller/quota" "github.com/goharbor/harbor/src/controller/quota"
"github.com/goharbor/harbor/src/core/config" "github.com/goharbor/harbor/src/core/config"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/pkg/errors"
) )
// InternalAPI handles request of harbor admin... // InternalAPI handles request of harbor admin...
@ -104,7 +103,7 @@ func (ia *InternalAPI) SwitchQuota() {
// SyncQuota ... // SyncQuota ...
func (ia *InternalAPI) SyncQuota() { func (ia *InternalAPI) SyncQuota() {
if !config.QuotaPerProjectEnable() { if !config.QuotaPerProjectEnable() {
ia.SendError(ierror.ForbiddenError(nil).WithMessage("quota per project is disabled")) ia.SendError(errors.ForbiddenError(nil).WithMessage("quota per project is disabled"))
return return
} }

View File

@ -1,13 +1,35 @@
package error // Copyright Project Harbor Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package errors
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"strings"
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
) )
var (
// As alias function of `errors.As`
As = errors.As
// Is alias function of `errors.Is`
Is = errors.Is
)
// Error ... // Error ...
type Error struct { type Error struct {
Cause error `json:"-"` Cause error `json:"-"`
@ -17,7 +39,23 @@ type Error struct {
// Error returns a human readable error. // Error returns a human readable error.
func (e *Error) Error() string { func (e *Error) Error() string {
return fmt.Sprintf("%v, %s, %s", e.Cause, e.Code, e.Message) var parts []string
var causeStr string
if e.Cause != nil {
causeStr = e.Cause.Error()
parts = append(parts, causeStr)
}
if e.Code != "" {
parts = append(parts, e.Code)
}
if e.Message != causeStr {
parts = append(parts, e.Message)
}
return strings.Join(parts, ", ")
} }
// WithMessage ... // WithMessage ...
@ -53,14 +91,15 @@ func (errs Errors) Error() string {
} }
for _, e := range errs { for _, e := range errs {
var err error err, ok := e.(*Error)
switch e.(type) { if !ok {
case *Error:
err = e.(*Error)
default:
err = UnknownError(e).WithMessage(e.Error()) err = UnknownError(e).WithMessage(e.Error())
} }
tmpErrs.Errors = append(tmpErrs.Errors, *err.(*Error)) if err.Code == "" {
err.Code = GeneralCode
}
tmpErrs.Errors = append(tmpErrs.Errors, *err)
} }
msg, err := json.Marshal(tmpErrs) msg, err := json.Marshal(tmpErrs)

View File

@ -12,11 +12,13 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
package error package errors
import ( import (
"errors" "errors"
"testing" "testing"
"github.com/stretchr/testify/suite"
) )
func TestErrCode(t *testing.T) { func TestErrCode(t *testing.T) {
@ -41,3 +43,18 @@ func TestErrCode(t *testing.T) {
}) })
} }
} }
type ErrorTestSuite struct {
suite.Suite
}
func (suite *ErrorTestSuite) TestNewCompatibleWithStdlib() {
err1 := New("oops")
err2 := errors.New("oops")
suite.Equal(err2.Error(), err1.Error())
}
func TestErrorTestSuite(t *testing.T) {
suite.Run(t, &ErrorTestSuite{})
}

View File

@ -15,10 +15,8 @@
package orm package orm
import ( import (
"errors"
"github.com/astaxie/beego/orm" "github.com/astaxie/beego/orm"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/lib/pq" "github.com/lib/pq"
) )
@ -42,9 +40,9 @@ func WrapConflictError(err error, format string, args ...interface{}) error {
// AsNotFoundError checks whether the err is orm.ErrNoRows. If it it, wrap it // AsNotFoundError checks whether the err is orm.ErrNoRows. If it it, wrap it
// as a src/internal/error.Error with not found error code, else return nil // as a src/internal/error.Error with not found error code, else return nil
func AsNotFoundError(err error, messageFormat string, args ...interface{}) *ierror.Error { func AsNotFoundError(err error, messageFormat string, args ...interface{}) *errors.Error {
if errors.Is(err, orm.ErrNoRows) { if errors.Is(err, orm.ErrNoRows) {
e := ierror.NotFoundError(err) e := errors.NotFoundError(err)
if len(messageFormat) > 0 { if len(messageFormat) > 0 {
e.WithMessage(messageFormat, args...) e.WithMessage(messageFormat, args...)
} }
@ -55,11 +53,11 @@ func AsNotFoundError(err error, messageFormat string, args ...interface{}) *ierr
// AsConflictError checks whether the err is duplicate key error. If it it, wrap it // AsConflictError checks whether the err is duplicate key error. If it it, wrap it
// as a src/internal/error.Error with conflict error code, else return nil // as a src/internal/error.Error with conflict error code, else return nil
func AsConflictError(err error, messageFormat string, args ...interface{}) *ierror.Error { func AsConflictError(err error, messageFormat string, args ...interface{}) *errors.Error {
var pqErr *pq.Error var pqErr *pq.Error
if errors.As(err, &pqErr) && pqErr.Code == "23505" { if errors.As(err, &pqErr) && pqErr.Code == "23505" {
e := ierror.New(err). e := errors.New(err).
WithCode(ierror.ConflictCode). WithCode(errors.ConflictCode).
WithMessage(messageFormat, args...) WithMessage(messageFormat, args...)
return e return e
} }
@ -68,11 +66,11 @@ func AsConflictError(err error, messageFormat string, args ...interface{}) *ierr
// AsForeignKeyError checks whether the err is violating foreign key constraint error. If it it, wrap it // AsForeignKeyError checks whether the err is violating foreign key constraint error. If it it, wrap it
// as a src/internal/error.Error with violating foreign key constraint error code, else return nil // as a src/internal/error.Error with violating foreign key constraint error code, else return nil
func AsForeignKeyError(err error, messageFormat string, args ...interface{}) *ierror.Error { func AsForeignKeyError(err error, messageFormat string, args ...interface{}) *errors.Error {
var pqErr *pq.Error var pqErr *pq.Error
if errors.As(err, &pqErr) && pqErr.Code == "23503" { if errors.As(err, &pqErr) && pqErr.Code == "23503" {
e := ierror.New(err). e := errors.New(err).
WithCode(ierror.ViolateForeignKeyConstraintCode). WithCode(errors.ViolateForeignKeyConstraintCode).
WithMessage(messageFormat, args...) WithMessage(messageFormat, args...)
return e return e
} }

View File

@ -15,9 +15,8 @@
package orm package orm
import ( import (
"errors"
"github.com/astaxie/beego/orm" "github.com/astaxie/beego/orm"
"github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/lib/pq" "github.com/lib/pq"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -37,7 +36,7 @@ func TestIsNotFoundError(t *testing.T) {
message := "message" message := "message"
err = AsNotFoundError(orm.ErrNoRows, message) err = AsNotFoundError(orm.ErrNoRows, message)
require.NotNil(t, err) require.NotNil(t, err)
assert.Equal(t, error.NotFoundCode, err.Code) assert.Equal(t, errors.NotFoundCode, err.Code)
assert.Equal(t, message, err.Message) assert.Equal(t, message, err.Message)
} }
@ -56,7 +55,7 @@ func TestIsConflictError(t *testing.T) {
Code: "23505", Code: "23505",
}, message) }, message)
require.NotNil(t, err) require.NotNil(t, err)
assert.Equal(t, error.ConflictCode, err.Code) assert.Equal(t, errors.ConflictCode, err.Code)
assert.Equal(t, message, err.Message) assert.Equal(t, message, err.Message)
} }
@ -75,6 +74,6 @@ func TestIsForeignKeyError(t *testing.T) {
Code: "23503", Code: "23503",
}, message) }, message)
require.NotNil(t, err) require.NotNil(t, err)
assert.Equal(t, error.ViolateForeignKeyConstraintCode, err.Code) assert.Equal(t, errors.ViolateForeignKeyConstraintCode, err.Code)
assert.Equal(t, message, err.Message) assert.Equal(t, message, err.Message)
} }

View File

@ -17,7 +17,7 @@ package q
import ( import (
"fmt" "fmt"
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"net/url" "net/url"
"strconv" "strconv"
"strings" "strings"
@ -50,14 +50,14 @@ func Build(q string, pageNumber, pageSize int64) (*Query, error) {
for _, param := range params { for _, param := range params {
strs := strings.SplitN(param, "=", 2) strs := strings.SplitN(param, "=", 2)
if len(strs) != 2 || len(strs[0]) == 0 || len(strs[1]) == 0 { if len(strs) != 2 || len(strs[0]) == 0 || len(strs[1]) == 0 {
return nil, ierror.New(nil). return nil, errors.New(nil).
WithCode(ierror.BadRequestCode). WithCode(errors.BadRequestCode).
WithMessage(`the query string must contain "=" and the key/value cannot be empty`) WithMessage(`the query string must contain "=" and the key/value cannot be empty`)
} }
value, err := parsePattern(strs[1]) value, err := parsePattern(strs[1])
if err != nil { if err != nil {
return nil, ierror.New(err). return nil, errors.New(err).
WithCode(ierror.BadRequestCode). WithCode(errors.BadRequestCode).
WithMessage("invalid query string value: %s", strs[1]) WithMessage("invalid query string value: %s", strs[1])
} }
query.Keywords[strs[0]] = value query.Keywords[strs[0]] = value

View File

@ -20,7 +20,7 @@ import (
"strings" "strings"
beegoorm "github.com/astaxie/beego/orm" beegoorm "github.com/astaxie/beego/orm"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
) )
@ -134,7 +134,7 @@ func (d *dao) GetByDigest(ctx context.Context, repository, digest string) (*Arti
return nil, err return nil, err
} }
if len(artifacts) == 0 { if len(artifacts) == 0 {
return nil, ierror.New(nil).WithCode(ierror.NotFoundCode). return nil, errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("artifact %s@%s not found", repository, digest) WithMessage("artifact %s@%s not found", repository, digest)
} }
return artifacts[0], nil return artifacts[0], nil
@ -170,7 +170,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return ierror.NotFoundError(nil).WithMessage("artifact %d not found", id) return errors.NotFoundError(nil).WithMessage("artifact %d not found", id)
} }
return nil return nil
@ -185,7 +185,7 @@ func (d *dao) Update(ctx context.Context, artifact *Artifact, props ...string) e
return err return err
} }
if n == 0 { if n == 0 {
return ierror.NotFoundError(nil).WithMessage("artifact %d not found", artifact.ID) return errors.NotFoundError(nil).WithMessage("artifact %d not found", artifact.ID)
} }
return nil return nil
} }
@ -228,7 +228,7 @@ func (d *dao) DeleteReference(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return ierror.NotFoundError(nil).WithMessage("artifact reference %d not found", id) return errors.NotFoundError(nil).WithMessage("artifact reference %d not found", id)
} }
return nil return nil
} }
@ -287,7 +287,7 @@ func setBaseQuery(qs beegoorm.QuerySeter, query *q.Query) (beegoorm.QuerySeter,
} }
b, ok := base.(string) b, ok := base.(string)
if !ok || b != "*" { if !ok || b != "*" {
return qs, ierror.New(nil).WithCode(ierror.BadRequestCode). return qs, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage(`the value of "base" query can only be exact match value with "*"`) WithMessage(`the value of "base" query can only be exact match value with "*"`)
} }
// the base is specified as "*" // the base is specified as "*"
@ -329,7 +329,7 @@ func setTagQuery(qs beegoorm.QuerySeter, query *q.Query) (beegoorm.QuerySeter, e
return qs, nil return qs, nil
} }
} }
return qs, ierror.New(nil).WithCode(ierror.BadRequestCode). return qs, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage(`the value of "tags" query can only be fuzzy match value or exact match value with "*" and "nil"`) WithMessage(`the value of "tags" query can only be fuzzy match value or exact match value with "*" and "nil"`)
} }
@ -347,14 +347,14 @@ func setLabelQuery(qs beegoorm.QuerySeter, query *q.Query) (beegoorm.QuerySeter,
} }
al, ok := labels.(*q.AndList) al, ok := labels.(*q.AndList)
if !ok { if !ok {
return qs, ierror.New(nil).WithCode(ierror.BadRequestCode). return qs, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage(`the value of "labels" query can only be integer list with intersetion relationship`) WithMessage(`the value of "labels" query can only be integer list with intersetion relationship`)
} }
var collections []string var collections []string
for _, value := range al.Values { for _, value := range al.Values {
labelID, ok := value.(int64) labelID, ok := value.(int64)
if !ok { if !ok {
return qs, ierror.New(nil).WithCode(ierror.BadRequestCode). return qs, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage(`the value of "labels" query can only be integer list with intersetion relationship`) WithMessage(`the value of "labels" query can only be integer list with intersetion relationship`)
} }
collections = append(collections, fmt.Sprintf(`SELECT artifact_id FROM label_reference WHERE label_id=%d`, labelID)) collections = append(collections, fmt.Sprintf(`SELECT artifact_id FROM label_reference WHERE label_id=%d`, labelID))

View File

@ -18,7 +18,7 @@ import (
"context" "context"
beegoorm "github.com/astaxie/beego/orm" beegoorm "github.com/astaxie/beego/orm"
common_dao "github.com/goharbor/harbor/src/common/dao" common_dao "github.com/goharbor/harbor/src/common/dao"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
tagdao "github.com/goharbor/harbor/src/pkg/tag/dao" tagdao "github.com/goharbor/harbor/src/pkg/tag/dao"
@ -177,7 +177,7 @@ func (d *daoTestSuite) TestCount() {
}, },
}) })
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.BadRequestCode)) d.True(errors.IsErr(err, errors.BadRequestCode))
// query by repository ID and digest // query by repository ID and digest
total, err := d.dao.Count(d.ctx, &q.Query{ total, err := d.dao.Count(d.ctx, &q.Query{
@ -316,7 +316,7 @@ func (d *daoTestSuite) TestGet() {
// get the non-exist artifact // get the non-exist artifact
_, err := d.dao.Get(d.ctx, 10000) _, err := d.dao.Get(d.ctx, 10000)
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.NotFoundCode)) d.True(errors.IsErr(err, errors.NotFoundCode))
// get the exist artifact // get the exist artifact
artifact, err := d.dao.Get(d.ctx, d.parentArtID) artifact, err := d.dao.Get(d.ctx, d.parentArtID)
@ -329,7 +329,7 @@ func (d *daoTestSuite) TestGetByDigest() {
// get the non-exist artifact // get the non-exist artifact
_, err := d.dao.GetByDigest(d.ctx, "library/hello-world", "non_existing_digest") _, err := d.dao.GetByDigest(d.ctx, "library/hello-world", "non_existing_digest")
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.NotFoundCode)) d.True(errors.IsErr(err, errors.NotFoundCode))
// get the exist artifact // get the exist artifact
artifact, err := d.dao.GetByDigest(d.ctx, "library/hello-world", "child_digest_02") artifact, err := d.dao.GetByDigest(d.ctx, "library/hello-world", "child_digest_02")
@ -357,7 +357,7 @@ func (d *daoTestSuite) TestCreate() {
} }
_, err := d.dao.Create(d.ctx, artifact) _, err := d.dao.Create(d.ctx, artifact)
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.ConflictCode)) d.True(errors.IsErr(err, errors.ConflictCode))
} }
func (d *daoTestSuite) TestDelete() { func (d *daoTestSuite) TestDelete() {
@ -366,12 +366,12 @@ func (d *daoTestSuite) TestDelete() {
// not exist // not exist
err := d.dao.Delete(d.ctx, 100021) err := d.dao.Delete(d.ctx, 100021)
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.NotFoundCode)) d.True(errors.IsErr(err, errors.NotFoundCode))
// foreign key constraint // foreign key constraint
err = d.dao.Delete(d.ctx, d.childArt01ID) err = d.dao.Delete(d.ctx, d.childArt01ID)
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.ViolateForeignKeyConstraintCode)) d.True(errors.IsErr(err, errors.ViolateForeignKeyConstraintCode))
} }
func (d *daoTestSuite) TestUpdate() { func (d *daoTestSuite) TestUpdate() {
@ -393,7 +393,7 @@ func (d *daoTestSuite) TestUpdate() {
ID: 10000, ID: 10000,
}) })
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.NotFoundCode)) d.True(errors.IsErr(err, errors.NotFoundCode))
} }
func (d *daoTestSuite) TestCreateReference() { func (d *daoTestSuite) TestCreateReference() {
@ -405,7 +405,7 @@ func (d *daoTestSuite) TestCreateReference() {
ChildID: d.childArt01ID, ChildID: d.childArt01ID,
}) })
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.ConflictCode)) d.True(errors.IsErr(err, errors.ConflictCode))
// foreign key constraint // foreign key constraint
_, err = d.dao.CreateReference(d.ctx, &ArtifactReference{ _, err = d.dao.CreateReference(d.ctx, &ArtifactReference{
@ -413,7 +413,7 @@ func (d *daoTestSuite) TestCreateReference() {
ChildID: 1000, ChildID: 1000,
}) })
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.ViolateForeignKeyConstraintCode)) d.True(errors.IsErr(err, errors.ViolateForeignKeyConstraintCode))
} }
func (d *daoTestSuite) TestListReferences() { func (d *daoTestSuite) TestListReferences() {
@ -432,7 +432,7 @@ func (d *daoTestSuite) TestDeleteReference() {
// not exist // not exist
err := d.dao.DeleteReference(d.ctx, 10000) err := d.dao.DeleteReference(d.ctx, 10000)
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.NotFoundCode)) d.True(errors.IsErr(err, errors.NotFoundCode))
} }
func (d *daoTestSuite) TestDeleteReferences() { func (d *daoTestSuite) TestDeleteReferences() {
@ -441,7 +441,7 @@ func (d *daoTestSuite) TestDeleteReferences() {
// parent artifact not exist // parent artifact not exist
err := d.dao.DeleteReferences(d.ctx, 10000) err := d.dao.DeleteReferences(d.ctx, 10000)
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.NotFoundCode)) d.True(errors.IsErr(err, errors.NotFoundCode))
} }
func TestDaoTestSuite(t *testing.T) { func TestDaoTestSuite(t *testing.T) {

View File

@ -4,7 +4,7 @@ import (
"context" "context"
"time" "time"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/pkg/artifactrash/model" "github.com/goharbor/harbor/src/pkg/artifactrash/model"
) )
@ -58,7 +58,7 @@ func (d *dao) Delete(ctx context.Context, id int64) (err error) {
return err return err
} }
if n == 0 { if n == 0 {
return ierror.NotFoundError(nil).WithMessage("artifact trash %d not found", id) return errors.NotFoundError(nil).WithMessage("artifact trash %d not found", id)
} }
return nil return nil
} }

View File

@ -2,10 +2,9 @@ package dao
import ( import (
"context" "context"
"errors"
beegoorm "github.com/astaxie/beego/orm" beegoorm "github.com/astaxie/beego/orm"
common_dao "github.com/goharbor/harbor/src/common/dao" common_dao "github.com/goharbor/harbor/src/common/dao"
ierror "github.com/goharbor/harbor/src/lib/error" errors "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
artdao "github.com/goharbor/harbor/src/pkg/artifact/dao" artdao "github.com/goharbor/harbor/src/pkg/artifact/dao"
"github.com/goharbor/harbor/src/pkg/artifactrash/model" "github.com/goharbor/harbor/src/pkg/artifactrash/model"
@ -73,15 +72,15 @@ func (d *daoTestSuite) TestCreate() {
_, err := d.dao.Create(d.ctx, aft) _, err := d.dao.Create(d.ctx, aft)
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.ConflictCode)) d.True(errors.IsErr(err, errors.ConflictCode))
} }
func (d *daoTestSuite) TestDelete() { func (d *daoTestSuite) TestDelete() {
err := d.dao.Delete(d.ctx, 100021) err := d.dao.Delete(d.ctx, 100021)
d.Require().NotNil(err) d.Require().NotNil(err)
var e *ierror.Error var e *errors.Error
d.Require().True(errors.As(err, &e)) d.Require().True(errors.As(err, &e))
d.Equal(ierror.NotFoundCode, e.Code) d.Equal(errors.NotFoundCode, e.Code)
} }
func (d *daoTestSuite) TestFilter() { func (d *daoTestSuite) TestFilter() {

View File

@ -16,7 +16,7 @@ package dao
import ( import (
"context" "context"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"github.com/goharbor/harbor/src/pkg/audit/model" "github.com/goharbor/harbor/src/pkg/audit/model"
@ -121,7 +121,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return ierror.NotFoundError(nil).WithMessage("access %d not found", id) return errors.NotFoundError(nil).WithMessage("access %d not found", id)
} }
return nil return nil
} }

View File

@ -16,10 +16,9 @@ package dao
import ( import (
"context" "context"
"errors"
beegoorm "github.com/astaxie/beego/orm" beegoorm "github.com/astaxie/beego/orm"
common_dao "github.com/goharbor/harbor/src/common/dao" common_dao "github.com/goharbor/harbor/src/common/dao"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"github.com/goharbor/harbor/src/pkg/audit/model" "github.com/goharbor/harbor/src/pkg/audit/model"
@ -86,7 +85,7 @@ func (d *daoTestSuite) TestGet() {
// get the non-exist tag // get the non-exist tag
_, err := d.dao.Get(d.ctx, 10000) _, err := d.dao.Get(d.ctx, 10000)
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.NotFoundCode)) d.True(errors.IsErr(err, errors.NotFoundCode))
audit, err := d.dao.Get(d.ctx, d.auditID) audit, err := d.dao.Get(d.ctx, d.auditID)
d.Require().Nil(err) d.Require().Nil(err)
@ -153,9 +152,9 @@ func (d *daoTestSuite) TestCreate() {
func (d *daoTestSuite) TestDelete() { func (d *daoTestSuite) TestDelete() {
err := d.dao.Delete(d.ctx, 10000) err := d.dao.Delete(d.ctx, 10000)
d.Require().NotNil(err) d.Require().NotNil(err)
var e *ierror.Error var e *errors.Error
d.Require().True(errors.As(err, &e)) d.Require().True(errors.As(err, &e))
d.Equal(ierror.NotFoundCode, e.Code) d.Equal(errors.NotFoundCode, e.Code)
} }
func TestDaoTestSuite(t *testing.T) { func TestDaoTestSuite(t *testing.T) {

View File

@ -3,10 +3,9 @@ package dao
import ( import (
"fmt" "fmt"
"errors"
"github.com/astaxie/beego/orm" "github.com/astaxie/beego/orm"
"github.com/goharbor/harbor/src/common/dao" "github.com/goharbor/harbor/src/common/dao"
internal_errors "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/immutabletag/dao/model" "github.com/goharbor/harbor/src/pkg/immutabletag/dao/model"
) )
@ -35,7 +34,7 @@ func (i *immutableRuleDao) CreateImmutableRule(ir *model.ImmutableRule) (int64,
id, err := o.Insert(ir) id, err := o.Insert(ir)
if err != nil { if err != nil {
if dao.IsDupRecErr(err) { if dao.IsDupRecErr(err) {
return id, internal_errors.ConflictError(err) return id, errors.ConflictError(err)
} }
return id, err return id, err
} }
@ -49,7 +48,7 @@ func (i *immutableRuleDao) UpdateImmutableRule(projectID int64, ir *model.Immuta
id, err := o.Update(ir, "TagFilter") id, err := o.Update(ir, "TagFilter")
if err != nil { if err != nil {
if errors.Is(err, orm.ErrNoRows) { if errors.Is(err, orm.ErrNoRows) {
return id, internal_errors.NotFoundError(err) return id, errors.NotFoundError(err)
} }
return id, err return id, err
} }
@ -63,7 +62,7 @@ func (i *immutableRuleDao) ToggleImmutableRule(id int64, status bool) (int64, er
id, err := o.Update(ir, "Disabled") id, err := o.Update(ir, "Disabled")
if err != nil { if err != nil {
if errors.Is(err, orm.ErrNoRows) { if errors.Is(err, orm.ErrNoRows) {
return id, internal_errors.NotFoundError(err) return id, errors.NotFoundError(err)
} }
return id, err return id, err
} }
@ -77,7 +76,7 @@ func (i *immutableRuleDao) GetImmutableRule(id int64) (*model.ImmutableRule, err
err := o.Read(ir) err := o.Read(ir)
if err != nil { if err != nil {
if errors.Is(err, orm.ErrNoRows) { if errors.Is(err, orm.ErrNoRows) {
return nil, internal_errors.New(err).WithCode(internal_errors.NotFoundCode). return nil, errors.New(err).WithCode(errors.NotFoundCode).
WithMessage(fmt.Sprintf("the immutable rule %d is not found.", id)) WithMessage(fmt.Sprintf("the immutable rule %d is not found.", id))
} }
return nil, err return nil, err

View File

@ -18,7 +18,7 @@ import (
"context" "context"
beego_orm "github.com/astaxie/beego/orm" beego_orm "github.com/astaxie/beego/orm"
"github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/models"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
) )
@ -95,7 +95,7 @@ func (d *defaultDAO) Delete(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return ierror.NotFoundError(nil).WithMessage("label %d not found", id) return errors.NotFoundError(nil).WithMessage("label %d not found", id)
} }
return nil return nil
} }
@ -126,7 +126,7 @@ func (d *defaultDAO) CreateReference(ctx context.Context, ref *Reference) (int64
err = e err = e
} else if e := orm.AsForeignKeyError(err, "the reference tries to refer a non existing label %d or artifact %d", } else if e := orm.AsForeignKeyError(err, "the reference tries to refer a non existing label %d or artifact %d",
ref.LabelID, ref.ArtifactID); e != nil { ref.LabelID, ref.ArtifactID); e != nil {
err = ierror.New(e).WithCode(ierror.NotFoundCode).WithMessage(e.Message) err = errors.New(e).WithCode(errors.NotFoundCode).WithMessage(e.Message)
} }
} }
return id, err return id, err
@ -144,7 +144,7 @@ func (d *defaultDAO) DeleteReference(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return ierror.NotFoundError(nil).WithMessage("label reference %d not found", id) return errors.NotFoundError(nil).WithMessage("label reference %d not found", id)
} }
return nil return nil
} }

View File

@ -19,7 +19,7 @@ import (
beegoorm "github.com/astaxie/beego/orm" beegoorm "github.com/astaxie/beego/orm"
common_dao "github.com/goharbor/harbor/src/common/dao" common_dao "github.com/goharbor/harbor/src/common/dao"
"github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/models"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
artdao "github.com/goharbor/harbor/src/pkg/artifact/dao" artdao "github.com/goharbor/harbor/src/pkg/artifact/dao"
@ -87,7 +87,7 @@ func (l *labelDaoTestSuite) TestGet() {
// not found // not found
_, err := l.dao.Get(l.ctx, 1000) _, err := l.dao.Get(l.ctx, 1000)
l.Require().NotNil(err) l.Require().NotNil(err)
l.True(ierror.IsErr(err, ierror.NotFoundCode)) l.True(errors.IsErr(err, errors.NotFoundCode))
// success // success
label, err := l.dao.Get(l.ctx, l.id) label, err := l.dao.Get(l.ctx, l.id)
@ -104,7 +104,7 @@ func (l *labelDaoTestSuite) TestCreate() {
Scope: "g", Scope: "g",
}) })
l.Require().NotNil(err) l.Require().NotNil(err)
l.True(ierror.IsErr(err, ierror.ConflictCode)) l.True(errors.IsErr(err, errors.ConflictCode))
} }
func (l *labelDaoTestSuite) TestDelete() { func (l *labelDaoTestSuite) TestDelete() {
@ -113,7 +113,7 @@ func (l *labelDaoTestSuite) TestDelete() {
// not found // not found
err := l.dao.Delete(l.ctx, 1000) err := l.dao.Delete(l.ctx, 1000)
l.Require().NotNil(err) l.Require().NotNil(err)
l.True(ierror.IsErr(err, ierror.NotFoundCode)) l.True(errors.IsErr(err, errors.NotFoundCode))
} }
func (l *labelDaoTestSuite) TestListByResource() { func (l *labelDaoTestSuite) TestListByResource() {
@ -132,7 +132,7 @@ func (l *labelDaoTestSuite) TestCreateReference() {
ArtifactID: l.artID, ArtifactID: l.artID,
}) })
l.Require().NotNil(err) l.Require().NotNil(err)
l.True(ierror.IsErr(err, ierror.ConflictCode)) l.True(errors.IsErr(err, errors.ConflictCode))
// violating foreign key constraint: the label that the ref tries to refer doesn't exist // violating foreign key constraint: the label that the ref tries to refer doesn't exist
_, err = l.dao.CreateReference(l.ctx, &Reference{ _, err = l.dao.CreateReference(l.ctx, &Reference{
@ -140,7 +140,7 @@ func (l *labelDaoTestSuite) TestCreateReference() {
ArtifactID: l.artID, ArtifactID: l.artID,
}) })
l.Require().NotNil(err) l.Require().NotNil(err)
l.True(ierror.IsErr(err, ierror.NotFoundCode)) l.True(errors.IsErr(err, errors.NotFoundCode))
// violating foreign key constraint: the artifact that the ref tries to refer doesn't exist // violating foreign key constraint: the artifact that the ref tries to refer doesn't exist
_, err = l.dao.CreateReference(l.ctx, &Reference{ _, err = l.dao.CreateReference(l.ctx, &Reference{
@ -148,7 +148,7 @@ func (l *labelDaoTestSuite) TestCreateReference() {
ArtifactID: 1000, ArtifactID: 1000,
}) })
l.Require().NotNil(err) l.Require().NotNil(err)
l.True(ierror.IsErr(err, ierror.NotFoundCode)) l.True(errors.IsErr(err, errors.NotFoundCode))
} }
func (l *labelDaoTestSuite) DeleteReference() { func (l *labelDaoTestSuite) DeleteReference() {
@ -157,7 +157,7 @@ func (l *labelDaoTestSuite) DeleteReference() {
// not found // not found
err := l.dao.DeleteReference(l.ctx, 1000) err := l.dao.DeleteReference(l.ctx, 1000)
l.Require().NotNil(err) l.Require().NotNil(err)
l.True(ierror.IsErr(err, ierror.NotFoundCode)) l.True(errors.IsErr(err, errors.NotFoundCode))
} }
func (l *labelDaoTestSuite) DeleteReferences() { func (l *labelDaoTestSuite) DeleteReferences() {

View File

@ -17,7 +17,7 @@ package label
import ( import (
"context" "context"
"github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/models"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"time" "time"
) )
@ -79,7 +79,7 @@ func (m *manager) RemoveFrom(ctx context.Context, labelID int64, artifactID int6
return err return err
} }
if n == 0 { if n == 0 {
return ierror.NotFoundError(nil).WithMessage("reference with label %d and artifact %d not found", labelID, artifactID) return errors.NotFoundError(nil).WithMessage("reference with label %d and artifact %d not found", labelID, artifactID)
} }
return nil return nil
} }

View File

@ -17,7 +17,7 @@ package label
import ( import (
"context" "context"
"github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/models"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"github.com/stretchr/testify/mock" "github.com/stretchr/testify/mock"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
@ -109,7 +109,7 @@ func (m *managerTestSuite) TestRemoveFrom() {
m.dao.On("DeleteReferences").Return(0, nil) m.dao.On("DeleteReferences").Return(0, nil)
err = m.mgr.RemoveFrom(nil, 1, 1) err = m.mgr.RemoveFrom(nil, 1, 1)
m.Require().NotNil(err) m.Require().NotNil(err)
m.True(ierror.IsErr(err, ierror.NotFoundCode)) m.True(errors.IsErr(err, errors.NotFoundCode))
} }
func (m *managerTestSuite) TestRemoveAllFrom() { func (m *managerTestSuite) TestRemoveAllFrom() {

View File

@ -18,7 +18,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
@ -128,14 +128,14 @@ func (a *authorizer) fetchToken(scopes []*scope) (*token, error) {
} }
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
message := fmt.Sprintf("http status code: %d, body: %s", resp.StatusCode, string(body)) message := fmt.Sprintf("http status code: %d, body: %s", resp.StatusCode, string(body))
code := ierror.GeneralCode code := errors.GeneralCode
switch resp.StatusCode { switch resp.StatusCode {
case http.StatusUnauthorized: case http.StatusUnauthorized:
code = ierror.UnAuthorizedCode code = errors.UnAuthorizedCode
case http.StatusForbidden: case http.StatusForbidden:
code = ierror.ForbiddenCode code = errors.ForbiddenCode
} }
return nil, ierror.New(nil).WithCode(code). return nil, errors.New(nil).WithCode(code).
WithMessage(message) WithMessage(message)
} }
token := &token{} token := &token{}

View File

@ -16,7 +16,7 @@ package bearer
import ( import (
"fmt" "fmt"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/registry/auth/basic" "github.com/goharbor/harbor/src/pkg/registry/auth/basic"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -43,7 +43,7 @@ func TestModify(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, server.URL, nil) req, _ := http.NewRequest(http.MethodGet, server.URL, nil)
err := authorizer.Modify(req) err := authorizer.Modify(req)
require.NotNil(t, err) require.NotNil(t, err)
assert.True(t, ierror.IsErr(err, ierror.UnAuthorizedCode)) assert.True(t, errors.IsErr(err, errors.UnAuthorizedCode))
// valid credential // valid credential
a = basic.NewAuthorizer("username", "password") a = basic.NewAuthorizer("username", "password")

View File

@ -33,7 +33,7 @@ import (
commonhttp "github.com/goharbor/harbor/src/common/http" commonhttp "github.com/goharbor/harbor/src/common/http"
"github.com/goharbor/harbor/src/core/config" "github.com/goharbor/harbor/src/core/config"
"github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/registry/auth" "github.com/goharbor/harbor/src/pkg/registry/auth"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
v1 "github.com/opencontainers/image-spec/specs-go/v1" v1 "github.com/opencontainers/image-spec/specs-go/v1"
@ -257,7 +257,7 @@ func (c *client) ManifestExist(repository, reference string) (bool, string, erro
} }
resp, err := c.do(req) resp, err := c.do(req)
if err != nil { if err != nil {
if ierror.IsErr(err, ierror.NotFoundCode) { if errors.IsErr(err, errors.NotFoundCode) {
return false, "", nil return false, "", nil
} }
return false, "", err return false, "", err
@ -320,7 +320,7 @@ func (c *client) DeleteManifest(repository, reference string) error {
return err return err
} }
if !exist { if !exist {
return ierror.New(nil).WithCode(ierror.NotFoundCode). return errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("%s:%s not found", repository, reference) WithMessage("%s:%s not found", repository, reference)
} }
reference = digest reference = digest
@ -344,7 +344,7 @@ func (c *client) BlobExist(repository, digest string) (bool, error) {
} }
resp, err := c.do(req) resp, err := c.do(req)
if err != nil { if err != nil {
if ierror.IsErr(err, ierror.NotFoundCode) { if errors.IsErr(err, errors.NotFoundCode) {
return false, nil return false, nil
} }
return false, err return false, err
@ -460,7 +460,7 @@ func (c *client) Copy(srcRepo, srcRef, dstRepo, dstRef string, override bool) er
} }
// the same name artifact exists, but not allowed to override // the same name artifact exists, but not allowed to override
if !override { if !override {
return ierror.New(nil).WithCode(ierror.PreconditionCode). return errors.New(nil).WithCode(errors.PreconditionCode).
WithMessage("the same name but different digest artifact exists, but the override is set to false") WithMessage("the same name but different digest artifact exists, but the override is set to false")
} }
} }
@ -536,16 +536,16 @@ func (c *client) do(req *http.Request) (*http.Response, error) {
return nil, err return nil, err
} }
message := fmt.Sprintf("http status code: %d, body: %s", resp.StatusCode, string(body)) message := fmt.Sprintf("http status code: %d, body: %s", resp.StatusCode, string(body))
code := ierror.GeneralCode code := errors.GeneralCode
switch resp.StatusCode { switch resp.StatusCode {
case http.StatusUnauthorized: case http.StatusUnauthorized:
code = ierror.UnAuthorizedCode code = errors.UnAuthorizedCode
case http.StatusForbidden: case http.StatusForbidden:
code = ierror.ForbiddenCode code = errors.ForbiddenCode
case http.StatusNotFound: case http.StatusNotFound:
code = ierror.NotFoundCode code = errors.NotFoundCode
} }
return nil, ierror.New(nil).WithCode(code). return nil, errors.New(nil).WithCode(code).
WithMessage(message) WithMessage(message)
} }
return resp, nil return resp, nil

View File

@ -18,7 +18,7 @@ import (
"context" "context"
o "github.com/astaxie/beego/orm" o "github.com/astaxie/beego/orm"
"github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/models"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"time" "time"
@ -115,7 +115,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return ierror.NotFoundError(nil).WithMessage("repository %d not found", id) return errors.NotFoundError(nil).WithMessage("repository %d not found", id)
} }
return nil return nil
} }
@ -130,7 +130,7 @@ func (d *dao) Update(ctx context.Context, repository *models.RepoRecord, props .
return err return err
} }
if n == 0 { if n == 0 {
return ierror.NotFoundError(nil).WithMessage("repository %d not found", repository.RepositoryID) return errors.NotFoundError(nil).WithMessage("repository %d not found", repository.RepositoryID)
} }
return nil return nil
} }
@ -149,7 +149,7 @@ func (d *dao) AddPullCount(ctx context.Context, id int64) error {
return err return err
} }
if num == 0 { if num == 0 {
return ierror.New(nil).WithMessage("failed to increase repository pull count: %d", id) return errors.New(nil).WithMessage("failed to increase repository pull count: %d", id)
} }
return nil return nil

View File

@ -16,12 +16,11 @@ package dao
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
beegoorm "github.com/astaxie/beego/orm" beegoorm "github.com/astaxie/beego/orm"
common_dao "github.com/goharbor/harbor/src/common/dao" common_dao "github.com/goharbor/harbor/src/common/dao"
"github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/models"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
@ -106,7 +105,7 @@ func (d *daoTestSuite) TestGet() {
// get the non-exist repository // get the non-exist repository
_, err := d.dao.Get(d.ctx, 10000) _, err := d.dao.Get(d.ctx, 10000)
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.NotFoundCode)) d.True(errors.IsErr(err, errors.NotFoundCode))
// get the exist repository // get the exist repository
repository, err := d.dao.Get(d.ctx, d.id) repository, err := d.dao.Get(d.ctx, d.id)
@ -125,7 +124,7 @@ func (d *daoTestSuite) TestCreate() {
} }
_, err := d.dao.Create(d.ctx, repository) _, err := d.dao.Create(d.ctx, repository)
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.ConflictCode)) d.True(errors.IsErr(err, errors.ConflictCode))
} }
func (d *daoTestSuite) TestDelete() { func (d *daoTestSuite) TestDelete() {
@ -134,9 +133,9 @@ func (d *daoTestSuite) TestDelete() {
// not exist // not exist
err := d.dao.Delete(d.ctx, 100021) err := d.dao.Delete(d.ctx, 100021)
d.Require().NotNil(err) d.Require().NotNil(err)
var e *ierror.Error var e *errors.Error
d.Require().True(errors.As(err, &e)) d.Require().True(errors.As(err, &e))
d.Equal(ierror.NotFoundCode, e.Code) d.Equal(errors.NotFoundCode, e.Code)
} }
func (d *daoTestSuite) TestUpdate() { func (d *daoTestSuite) TestUpdate() {
@ -157,9 +156,9 @@ func (d *daoTestSuite) TestUpdate() {
RepositoryID: 10000, RepositoryID: 10000,
}) })
d.Require().NotNil(err) d.Require().NotNil(err)
var e *ierror.Error var e *errors.Error
d.Require().True(errors.As(err, &e)) d.Require().True(errors.As(err, &e))
d.Equal(ierror.NotFoundCode, e.Code) d.Equal(errors.NotFoundCode, e.Code)
} }
func (d *daoTestSuite) TestAddPullCount() { func (d *daoTestSuite) TestAddPullCount() {

View File

@ -17,7 +17,7 @@ package repository
import ( import (
"context" "context"
"github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/models"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"github.com/goharbor/harbor/src/pkg/repository/dao" "github.com/goharbor/harbor/src/pkg/repository/dao"
) )
@ -82,7 +82,7 @@ func (m *manager) GetByName(ctx context.Context, name string) (repository *model
return nil, err return nil, err
} }
if len(repositories) == 0 { if len(repositories) == 0 {
return nil, ierror.New(nil).WithCode(ierror.NotFoundCode). return nil, errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("repository %s not found", name) WithMessage("repository %s not found", name)
} }
return repositories[0], nil return repositories[0], nil

View File

@ -18,12 +18,11 @@ import (
"time" "time"
"github.com/goharbor/harbor/src/jobservice/job" "github.com/goharbor/harbor/src/jobservice/job"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"github.com/goharbor/harbor/src/pkg/scan/all" "github.com/goharbor/harbor/src/pkg/scan/all"
"github.com/goharbor/harbor/src/pkg/scan/dao/scan" "github.com/goharbor/harbor/src/pkg/scan/dao/scan"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/pkg/errors"
) )
const ( const (
@ -80,7 +79,7 @@ func (bm *basicManager) Create(r *scan.Report) (string, error) {
// Status conflict // Status conflict
if theCopy.StartTime.Add(reportTimeout).After(time.Now()) { if theCopy.StartTime.Add(reportTimeout).After(time.Now()) {
if theStatus.Compare(job.RunningStatus) <= 0 { if theStatus.Compare(job.RunningStatus) <= 0 {
return "", ierror.ConflictError(nil).WithMessage("a previous scan process is %s", theCopy.Status) return "", errors.ConflictError(nil).WithMessage("a previous scan process is %s", theCopy.Status)
} }
} }

View File

@ -17,7 +17,7 @@ package dao
import ( import (
"context" "context"
beego_orm "github.com/astaxie/beego/orm" beego_orm "github.com/astaxie/beego/orm"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"github.com/goharbor/harbor/src/pkg/tag/model/tag" "github.com/goharbor/harbor/src/pkg/tag/model/tag"
@ -123,7 +123,7 @@ func (d *dao) Update(ctx context.Context, tag *tag.Tag, props ...string) error {
return err return err
} }
if n == 0 { if n == 0 {
return ierror.NotFoundError(nil).WithMessage("tag %d not found", tag.ID) return errors.NotFoundError(nil).WithMessage("tag %d not found", tag.ID)
} }
return nil return nil
} }
@ -139,7 +139,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return ierror.NotFoundError(nil).WithMessage("tag %d not found", id) return errors.NotFoundError(nil).WithMessage("tag %d not found", id)
} }
return nil return nil
} }

View File

@ -16,10 +16,9 @@ package dao
import ( import (
"context" "context"
"errors"
beegoorm "github.com/astaxie/beego/orm" beegoorm "github.com/astaxie/beego/orm"
common_dao "github.com/goharbor/harbor/src/common/dao" common_dao "github.com/goharbor/harbor/src/common/dao"
ierror "github.com/goharbor/harbor/src/lib/error" errors "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
artdao "github.com/goharbor/harbor/src/pkg/artifact/dao" artdao "github.com/goharbor/harbor/src/pkg/artifact/dao"
@ -123,7 +122,7 @@ func (d *daoTestSuite) TestGet() {
// get the non-exist tag // get the non-exist tag
_, err := d.dao.Get(d.ctx, 10000) _, err := d.dao.Get(d.ctx, 10000)
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.NotFoundCode)) d.True(errors.IsErr(err, errors.NotFoundCode))
// get the exist tag // get the exist tag
tag, err := d.dao.Get(d.ctx, d.tagID) tag, err := d.dao.Get(d.ctx, d.tagID)
@ -145,7 +144,7 @@ func (d *daoTestSuite) TestCreate() {
} }
_, err := d.dao.Create(d.ctx, tg) _, err := d.dao.Create(d.ctx, tg)
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.ConflictCode)) d.True(errors.IsErr(err, errors.ConflictCode))
// violating foreign key constraint: the artifact that the tag tries to attach doesn't exist // violating foreign key constraint: the artifact that the tag tries to attach doesn't exist
tg = &tag.Tag{ tg = &tag.Tag{
@ -157,7 +156,7 @@ func (d *daoTestSuite) TestCreate() {
} }
_, err = d.dao.Create(d.ctx, tg) _, err = d.dao.Create(d.ctx, tg)
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.ViolateForeignKeyConstraintCode)) d.True(errors.IsErr(err, errors.ViolateForeignKeyConstraintCode))
} }
func (d *daoTestSuite) TestDelete() { func (d *daoTestSuite) TestDelete() {
@ -166,9 +165,9 @@ func (d *daoTestSuite) TestDelete() {
// not exist // not exist
err := d.dao.Delete(d.ctx, 10000) err := d.dao.Delete(d.ctx, 10000)
d.Require().NotNil(err) d.Require().NotNil(err)
var e *ierror.Error var e *errors.Error
d.Require().True(errors.As(err, &e)) d.Require().True(errors.As(err, &e))
d.Equal(ierror.NotFoundCode, e.Code) d.Equal(errors.NotFoundCode, e.Code)
} }
func (d *daoTestSuite) TestUpdate() { func (d *daoTestSuite) TestUpdate() {
@ -210,16 +209,16 @@ func (d *daoTestSuite) TestUpdate() {
ArtifactID: 2, ArtifactID: 2,
}, "ArtifactID") }, "ArtifactID")
d.Require().NotNil(err) d.Require().NotNil(err)
d.True(ierror.IsErr(err, ierror.ViolateForeignKeyConstraintCode)) d.True(errors.IsErr(err, errors.ViolateForeignKeyConstraintCode))
// not exist // not exist
err = d.dao.Update(d.ctx, &tag.Tag{ err = d.dao.Update(d.ctx, &tag.Tag{
ID: 10000, ID: 10000,
}) })
d.Require().NotNil(err) d.Require().NotNil(err)
var e *ierror.Error var e *errors.Error
d.Require().True(errors.As(err, &e)) d.Require().True(errors.As(err, &e))
d.Equal(ierror.NotFoundCode, e.Code) d.Equal(errors.NotFoundCode, e.Code)
} }
func (d *daoTestSuite) TestDeleteOfArtifact() { func (d *daoTestSuite) TestDeleteOfArtifact() {

View File

@ -15,13 +15,12 @@
package native package native
import ( import (
"errors"
"fmt" "fmt"
"github.com/goharbor/harbor/src/common/utils" "github.com/goharbor/harbor/src/common/utils"
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/registry" "github.com/goharbor/harbor/src/pkg/registry"
adp "github.com/goharbor/harbor/src/replication/adapter" adp "github.com/goharbor/harbor/src/replication/adapter"
"github.com/goharbor/harbor/src/replication/filter" "github.com/goharbor/harbor/src/replication/filter"
@ -237,7 +236,7 @@ func (a *Adapter) PingSimple() error {
if err == nil { if err == nil {
return nil return nil
} }
if ierror.IsErr(err, ierror.UnAuthorizedCode) || ierror.IsErr(err, ierror.ForbiddenCode) { if errors.IsErr(err, errors.UnAuthorizedCode) || errors.IsErr(err, errors.ForbiddenCode) {
return nil return nil
} }
return err return err

View File

@ -15,31 +15,30 @@
package error package error
import ( import (
"errors"
"fmt" "fmt"
openapi "github.com/go-openapi/errors" openapi "github.com/go-openapi/errors"
"github.com/go-openapi/runtime" "github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/middleware" "github.com/go-openapi/runtime/middleware"
commonhttp "github.com/goharbor/harbor/src/common/http" commonhttp "github.com/goharbor/harbor/src/common/http"
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"net/http" "net/http"
"strings" "strings"
) )
var ( var (
codeMap = map[string]int{ codeMap = map[string]int{
ierror.BadRequestCode: http.StatusBadRequest, errors.BadRequestCode: http.StatusBadRequest,
ierror.DIGESTINVALID: http.StatusBadRequest, errors.DIGESTINVALID: http.StatusBadRequest,
ierror.UnAuthorizedCode: http.StatusUnauthorized, errors.UnAuthorizedCode: http.StatusUnauthorized,
ierror.ForbiddenCode: http.StatusForbidden, errors.ForbiddenCode: http.StatusForbidden,
ierror.DENIED: http.StatusForbidden, errors.DENIED: http.StatusForbidden,
ierror.NotFoundCode: http.StatusNotFound, errors.NotFoundCode: http.StatusNotFound,
ierror.ConflictCode: http.StatusConflict, errors.ConflictCode: http.StatusConflict,
ierror.PreconditionCode: http.StatusPreconditionFailed, errors.PreconditionCode: http.StatusPreconditionFailed,
ierror.ViolateForeignKeyConstraintCode: http.StatusPreconditionFailed, errors.ViolateForeignKeyConstraintCode: http.StatusPreconditionFailed,
ierror.PROJECTPOLICYVIOLATION: http.StatusPreconditionFailed, errors.PROJECTPOLICYVIOLATION: http.StatusPreconditionFailed,
ierror.GeneralCode: http.StatusInternalServerError, errors.GeneralCode: http.StatusInternalServerError,
} }
) )
@ -52,8 +51,8 @@ func SendError(w http.ResponseWriter, err error) {
// the error detail is logged only, and will not be sent to the client to avoid leaking server information // the error detail is logged only, and will not be sent to the client to avoid leaking server information
if statusCode >= http.StatusInternalServerError { if statusCode >= http.StatusInternalServerError {
log.Error(errPayload) log.Error(errPayload)
err = ierror.New(nil).WithCode(ierror.GeneralCode).WithMessage("internal server error") err = errors.New(nil).WithCode(errors.GeneralCode).WithMessage("internal server error")
errPayload = ierror.NewErrs(err).Error() errPayload = errors.NewErrs(err).Error()
} else { } else {
// only log the error whose status code < 500 when debugging to avoid log flooding // only log the error whose status code < 500 when debugging to avoid log flooding
log.Debug(errPayload) log.Debug(errPayload)
@ -74,19 +73,19 @@ func apiError(err error) (statusCode int, errPayload string) {
// So we needed to convert the format to the internal error response format. // So we needed to convert the format to the internal error response format.
code = int(openAPIErr.Code()) code = int(openAPIErr.Code())
errCode := strings.Replace(strings.ToUpper(http.StatusText(code)), " ", "_", -1) errCode := strings.Replace(strings.ToUpper(http.StatusText(code)), " ", "_", -1)
err = ierror.New(nil).WithCode(errCode).WithMessage(openAPIErr.Error()) err = errors.New(nil).WithCode(errCode).WithMessage(openAPIErr.Error())
} else if legacyErr, ok := err.(*commonhttp.Error); ok { } else if legacyErr, ok := err.(*commonhttp.Error); ok {
// make sure the legacy error format is align with the new one // make sure the legacy error format is align with the new one
code = legacyErr.Code code = legacyErr.Code
errCode := strings.Replace(strings.ToUpper(http.StatusText(code)), " ", "_", -1) errCode := strings.Replace(strings.ToUpper(http.StatusText(code)), " ", "_", -1)
err = ierror.New(nil).WithCode(errCode).WithMessage(legacyErr.Message) err = errors.New(nil).WithCode(errCode).WithMessage(legacyErr.Message)
} else { } else {
code = codeMap[ierror.ErrCode(err)] code = codeMap[errors.ErrCode(err)]
} }
if code == 0 { if code == 0 {
code = http.StatusInternalServerError code = http.StatusInternalServerError
} }
return code, ierror.NewErrs(err).Error() return code, errors.NewErrs(err).Error()
} }
var _ middleware.Responder = &ErrResponder{} var _ middleware.Responder = &ErrResponder{}

View File

@ -15,10 +15,9 @@
package error package error
import ( import (
"errors"
openapi "github.com/go-openapi/errors" openapi "github.com/go-openapi/errors"
commonhttp "github.com/goharbor/harbor/src/common/http" commonhttp "github.com/goharbor/harbor/src/common/http"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@ -28,21 +27,21 @@ import (
func TestSendError(t *testing.T) { func TestSendError(t *testing.T) {
// unauthorized error // unauthorized error
rw := httptest.NewRecorder() rw := httptest.NewRecorder()
err := ierror.New(nil).WithCode(ierror.UnAuthorizedCode).WithMessage("unauthorized") err := errors.New(nil).WithCode(errors.UnAuthorizedCode).WithMessage("unauthorized")
SendError(rw, err) SendError(rw, err)
assert.Equal(t, http.StatusUnauthorized, rw.Code) assert.Equal(t, http.StatusUnauthorized, rw.Code)
assert.Equal(t, `{"errors":[{"code":"UNAUTHORIZED","message":"unauthorized"}]}`+"\n", rw.Body.String()) assert.Equal(t, `{"errors":[{"code":"UNAUTHORIZED","message":"unauthorized"}]}`+"\n", rw.Body.String())
// internal server error // internal server error
rw = httptest.NewRecorder() rw = httptest.NewRecorder()
err = ierror.New(nil).WithCode(ierror.GeneralCode).WithMessage("unknown") err = errors.New(nil).WithCode(errors.GeneralCode).WithMessage("unknown")
SendError(rw, err) SendError(rw, err)
assert.Equal(t, http.StatusInternalServerError, rw.Code) assert.Equal(t, http.StatusInternalServerError, rw.Code)
assert.Equal(t, `{"errors":[{"code":"UNKNOWN","message":"internal server error"}]}`+"\n", rw.Body.String()) assert.Equal(t, `{"errors":[{"code":"UNKNOWN","message":"internal server error"}]}`+"\n", rw.Body.String())
// not internal server error // not internal server error
rw = httptest.NewRecorder() rw = httptest.NewRecorder()
err = ierror.New(nil).WithCode(ierror.NotFoundCode).WithMessage("object not found") err = errors.New(nil).WithCode(errors.NotFoundCode).WithMessage("object not found")
SendError(rw, err) SendError(rw, err)
assert.Equal(t, http.StatusNotFound, rw.Code) assert.Equal(t, http.StatusNotFound, rw.Code)
assert.Equal(t, `{"errors":[{"code":"NOT_FOUND","message":"object not found"}]}`+"\n", rw.Body.String()) assert.Equal(t, `{"errors":[{"code":"NOT_FOUND","message":"object not found"}]}`+"\n", rw.Body.String())
@ -65,10 +64,10 @@ func TestAPIError(t *testing.T) {
assert.Equal(t, http.StatusNotFound, statusCode) assert.Equal(t, http.StatusNotFound, statusCode)
assert.Equal(t, `{"errors":[{"code":"NOT_FOUND","message":"not found"}]}`, payload) assert.Equal(t, `{"errors":[{"code":"NOT_FOUND","message":"not found"}]}`, payload)
// ierror.Error // errors.Error
err = &ierror.Error{ err = &errors.Error{
Cause: nil, Cause: nil,
Code: ierror.NotFoundCode, Code: errors.NotFoundCode,
Message: "resource not found", Message: "resource not found",
} }
statusCode, payload = apiError(err) statusCode, payload = apiError(err)

View File

@ -23,7 +23,7 @@ import (
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
serror "github.com/goharbor/harbor/src/server/error" serror "github.com/goharbor/harbor/src/server/error"
"github.com/goharbor/harbor/src/server/middleware" "github.com/goharbor/harbor/src/server/middleware"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
@ -59,7 +59,7 @@ func Middleware() func(http.Handler) http.Handler {
repo := m[middleware.RepositorySubexp] repo := m[middleware.RepositorySubexp]
pn, err := projectNameFromRepo(repo) pn, err := projectNameFromRepo(repo)
if err != nil { if err != nil {
serror.SendError(rw, ierror.BadRequestError(err)) serror.SendError(rw, errors.BadRequestError(err))
return return
} }
art := lib.ArtifactInfo{ art := lib.ArtifactInfo{
@ -80,7 +80,7 @@ func Middleware() func(http.Handler) http.Handler {
// it's not clear in OCI spec how to handle invalid from parm // it's not clear in OCI spec how to handle invalid from parm
bmp, err := projectNameFromRepo(bmr) bmp, err := projectNameFromRepo(bmr)
if err != nil { if err != nil {
serror.SendError(rw, ierror.BadRequestError(err)) serror.SendError(rw, errors.BadRequestError(err))
return return
} }
art.BlobMountDigest = m[blobMountDigest] art.BlobMountDigest = m[blobMountDigest]

View File

@ -34,7 +34,7 @@ import (
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/controller/artifact" "github.com/goharbor/harbor/src/controller/artifact"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/blob" "github.com/goharbor/harbor/src/pkg/blob"
"github.com/goharbor/harbor/src/pkg/distribution" "github.com/goharbor/harbor/src/pkg/distribution"
"github.com/goharbor/harbor/src/server/middleware" "github.com/goharbor/harbor/src/server/middleware"
@ -61,9 +61,9 @@ func CopyArtifactMiddleware() func(http.Handler) http.Handler {
repository, reference, _ := distribution.ParseRef(from) repository, reference, _ := distribution.ParseRef(from)
art, err := artifactController.GetByReference(ctx, repository, reference, nil) art, err := artifactController.GetByReference(ctx, repository, reference, nil)
if ierror.IsNotFoundErr(err) { if errors.IsNotFoundErr(err) {
// artifact not found, discontinue the API request // artifact not found, discontinue the API request
return ierror.BadRequestError(nil).WithMessage("artifact %s not found", from) return errors.BadRequestError(nil).WithMessage("artifact %s not found", from)
} else if err != nil { } else if err != nil {
logger.Errorf("get artifact %s failed, error: %v", from, err) logger.Errorf("get artifact %s failed, error: %v", from, err)
return err return err

View File

@ -8,7 +8,7 @@ import (
"github.com/goharbor/harbor/src/common/security" "github.com/goharbor/harbor/src/common/security"
"github.com/goharbor/harbor/src/controller/project" "github.com/goharbor/harbor/src/controller/project"
"github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib"
internal_errors "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/signature" "github.com/goharbor/harbor/src/pkg/signature"
serror "github.com/goharbor/harbor/src/server/error" serror "github.com/goharbor/harbor/src/server/error"
"github.com/goharbor/harbor/src/server/middleware" "github.com/goharbor/harbor/src/server/middleware"
@ -35,7 +35,7 @@ func Middleware() func(http.Handler) http.Handler {
return return
} }
if !match { if !match {
pkgE := internal_errors.New(nil).WithCode(internal_errors.PROJECTPOLICYVIOLATION).WithMessage("The image is not signed in Notary.") pkgE := errors.New(nil).WithCode(errors.PROJECTPOLICYVIOLATION).WithMessage("The image is not signed in Notary.")
serror.SendError(rw, pkgE) serror.SendError(rw, pkgE)
return return
} }

View File

@ -10,7 +10,7 @@ import (
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/core/config" "github.com/goharbor/harbor/src/core/config"
"github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
serror "github.com/goharbor/harbor/src/server/error" serror "github.com/goharbor/harbor/src/server/error"
"github.com/goharbor/harbor/src/server/middleware" "github.com/goharbor/harbor/src/server/middleware"
"github.com/gorilla/csrf" "github.com/gorilla/csrf"
@ -45,7 +45,7 @@ func attachToken(w http.ResponseWriter, r *http.Request) {
func handleError(w http.ResponseWriter, r *http.Request) { func handleError(w http.ResponseWriter, r *http.Request) {
attachToken(w, r) attachToken(w, r)
serror.SendError(w, ierror.New(csrf.FailureReason(r)).WithCode(ierror.ForbiddenCode)) serror.SendError(w, errors.New(csrf.FailureReason(r)).WithCode(errors.ForbiddenCode))
return return
} }

View File

@ -1,7 +1,6 @@
package immutable package immutable
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
@ -10,7 +9,7 @@ import (
"github.com/goharbor/harbor/src/controller/artifact" "github.com/goharbor/harbor/src/controller/artifact"
"github.com/goharbor/harbor/src/controller/tag" "github.com/goharbor/harbor/src/controller/tag"
"github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib"
internal_errors "github.com/goharbor/harbor/src/lib/error" errors "github.com/goharbor/harbor/src/lib/errors"
serror "github.com/goharbor/harbor/src/server/error" serror "github.com/goharbor/harbor/src/server/error"
) )
@ -21,11 +20,11 @@ func Middleware() func(http.Handler) http.Handler {
if err := handlePush(req); err != nil { if err := handlePush(req); err != nil {
var e *ErrImmutable var e *ErrImmutable
if errors.As(err, &e) { if errors.As(err, &e) {
pkgE := internal_errors.New(e).WithCode(internal_errors.PreconditionCode) pkgE := errors.New(e).WithCode(errors.PreconditionCode)
serror.SendError(rw, pkgE) serror.SendError(rw, pkgE)
return return
} }
pkgE := internal_errors.New(fmt.Errorf("error occurred when to handle request in immutable handler: %v", err)).WithCode(internal_errors.GeneralCode) pkgE := errors.New(fmt.Errorf("error occurred when to handle request in immutable handler: %v", err)).WithCode(errors.GeneralCode)
serror.SendError(rw, pkgE) serror.SendError(rw, pkgE)
return return
} }

View File

@ -38,7 +38,7 @@ import (
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/controller/artifact" "github.com/goharbor/harbor/src/controller/artifact"
"github.com/goharbor/harbor/src/controller/event/metadata" "github.com/goharbor/harbor/src/controller/event/metadata"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"github.com/goharbor/harbor/src/pkg/blob" "github.com/goharbor/harbor/src/pkg/blob"
"github.com/goharbor/harbor/src/pkg/distribution" "github.com/goharbor/harbor/src/pkg/distribution"
@ -85,9 +85,9 @@ func copyArtifactResources(r *http.Request, reference, referenceID string) (type
ctx := r.Context() ctx := r.Context()
art, err := artifactController.GetByReference(ctx, repository, reference, nil) art, err := artifactController.GetByReference(ctx, repository, reference, nil)
if ierror.IsNotFoundErr(err) { if errors.IsNotFoundErr(err) {
// artifact not found, discontinue the API request // artifact not found, discontinue the API request
return nil, ierror.BadRequestError(nil).WithMessage("artifact %s not found", from) return nil, errors.BadRequestError(nil).WithMessage("artifact %s not found", from)
} else if err != nil { } else if err != nil {
logger.Errorf("get artifact %s failed, error: %v", from, err) logger.Errorf("get artifact %s failed, error: %v", from, err)
return nil, err return nil, err

View File

@ -20,7 +20,7 @@ import (
"github.com/goharbor/harbor/src/common/utils/log" "github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/controller/blob" "github.com/goharbor/harbor/src/controller/blob"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/types" "github.com/goharbor/harbor/src/pkg/types"
) )
@ -45,7 +45,7 @@ func postInitiateBlobUploadResources(r *http.Request, reference, referenceID str
logger := log.G(ctx).WithFields(log.Fields{"middleware": "quota", "action": "request", "url": r.URL.Path}) logger := log.G(ctx).WithFields(log.Fields{"middleware": "quota", "action": "request", "url": r.URL.Path})
blb, err := blobController.Get(ctx, mount) blb, err := blobController.Get(ctx, mount)
if ierror.IsNotFoundErr(err) { if errors.IsNotFoundErr(err) {
// mount blob not found, skip to request the resources // mount blob not found, skip to request the resources
return nil, nil return nil, nil
} else if err != nil { } else if err != nil {

View File

@ -22,7 +22,7 @@ import (
"github.com/docker/distribution/manifest/schema2" "github.com/docker/distribution/manifest/schema2"
commonmodels "github.com/goharbor/harbor/src/common/models" commonmodels "github.com/goharbor/harbor/src/common/models"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/blob/models" "github.com/goharbor/harbor/src/pkg/blob/models"
"github.com/goharbor/harbor/src/pkg/distribution" "github.com/goharbor/harbor/src/pkg/distribution"
"github.com/goharbor/harbor/src/pkg/notification" "github.com/goharbor/harbor/src/pkg/notification"
@ -216,7 +216,7 @@ func (suite *PutManifestMiddlewareTestSuite) TestResourcesExceeded() {
errs = errs.Add(quota.NewResourceOverflowError(types.ResourceCount, 10, 10, 11)) errs = errs.Add(quota.NewResourceOverflowError(types.ResourceCount, 10, 10, 11))
errs = errs.Add(quota.NewResourceOverflowError(types.ResourceStorage, 100, 100, 110)) errs = errs.Add(quota.NewResourceOverflowError(types.ResourceStorage, 100, 100, 110))
err := ierror.DeniedError(errs).WithMessage("Quota exceeded when processing the request of %v", errs) err := errors.DeniedError(errs).WithMessage("Quota exceeded when processing the request of %v", errs)
mock.OnAnything(suite.quotaController, "Request").Return(err).Once() mock.OnAnything(suite.quotaController, "Request").Return(err).Once()
req := httptest.NewRequest(http.MethodPut, "/v2/library/photon/manifests/2.0", nil) req := httptest.NewRequest(http.MethodPut, "/v2/library/photon/manifests/2.0", nil)

View File

@ -19,7 +19,7 @@ import (
"net/http" "net/http"
"github.com/goharbor/harbor/src/core/config" "github.com/goharbor/harbor/src/core/config"
internal_errors "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/server/middleware" "github.com/goharbor/harbor/src/server/middleware"
) )
@ -69,7 +69,7 @@ func MiddlewareWithConfig(config Config, skippers ...middleware.Skipper) func(ht
return middleware.New(func(w http.ResponseWriter, r *http.Request, next http.Handler) { return middleware.New(func(w http.ResponseWriter, r *http.Request, next http.Handler) {
if config.ReadOnly(r) { if config.ReadOnly(r) {
pkgE := internal_errors.New(nil).WithCode(internal_errors.DENIED).WithMessage("The system is in read only mode. Any modification is prohibited.") pkgE := errors.New(nil).WithCode(errors.DENIED).WithMessage("The system is in read only mode. Any modification is prohibited.")
serror.SendError(w, pkgE) serror.SendError(w, pkgE)
return return
} }

View File

@ -15,7 +15,6 @@
package v2auth package v2auth
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"sync" "sync"
@ -26,7 +25,7 @@ import (
"github.com/goharbor/harbor/src/core/config" "github.com/goharbor/harbor/src/core/config"
"github.com/goharbor/harbor/src/core/promgr" "github.com/goharbor/harbor/src/core/promgr"
"github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
serror "github.com/goharbor/harbor/src/server/error" serror "github.com/goharbor/harbor/src/server/error"
"github.com/goharbor/harbor/src/server/middleware" "github.com/goharbor/harbor/src/server/middleware"
) )
@ -135,7 +134,7 @@ func Middleware() func(http.Handler) http.Handler {
// the header is needed for "docker manifest" commands: https://github.com/docker/cli/issues/989 // the header is needed for "docker manifest" commands: https://github.com/docker/cli/issues/989
rw.Header().Set("Docker-Distribution-Api-Version", "registry/2.0") rw.Header().Set("Docker-Distribution-Api-Version", "registry/2.0")
rw.Header().Set("Www-Authenticate", `Basic realm="harbor"`) rw.Header().Set("Www-Authenticate", `Basic realm="harbor"`)
serror.SendError(rw, ierror.UnauthorizedError(err).WithMessage(err.Error())) serror.SendError(rw, errors.UnauthorizedError(err).WithMessage(err.Error()))
return return
} }
next.ServeHTTP(rw, req) next.ServeHTTP(rw, req)

View File

@ -25,7 +25,7 @@ import (
"github.com/goharbor/harbor/src/controller/project" "github.com/goharbor/harbor/src/controller/project"
"github.com/goharbor/harbor/src/controller/scan" "github.com/goharbor/harbor/src/controller/scan"
"github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/scan/report" "github.com/goharbor/harbor/src/pkg/scan/report"
v1 "github.com/goharbor/harbor/src/pkg/scan/rest/v1" v1 "github.com/goharbor/harbor/src/pkg/scan/rest/v1"
"github.com/goharbor/harbor/src/pkg/scan/vuln" "github.com/goharbor/harbor/src/pkg/scan/vuln"
@ -53,7 +53,7 @@ func Middleware() func(http.Handler) http.Handler {
art, err := artifactController.GetByReference(ctx, info.Repository, info.Reference, nil) art, err := artifactController.GetByReference(ctx, info.Repository, info.Reference, nil)
if err != nil { if err != nil {
if !ierror.IsNotFoundErr(err) { if !errors.IsNotFoundErr(err) {
logger.Errorf("get artifact failed, error %v", err) logger.Errorf("get artifact failed, error %v", err)
} }
return err return err
@ -105,7 +105,7 @@ func Middleware() func(http.Handler) http.Handler {
if !ok { if !ok {
// No report yet? // No report yet?
msg := "vulnerability prevention enabled, but no scan report existing for the artifact" msg := "vulnerability prevention enabled, but no scan report existing for the artifact"
return ierror.New(nil).WithCode(ierror.PROJECTPOLICYVIOLATION).WithMessage(msg) return errors.New(nil).WithCode(errors.PROJECTPOLICYVIOLATION).WithMessage(msg)
} }
summary, ok := rawSummary.(*vuln.NativeReportSummary) summary, ok := rawSummary.(*vuln.NativeReportSummary)
@ -130,7 +130,7 @@ func Middleware() func(http.Handler) http.Handler {
if summary.Severity.Code() >= severity.Code() { if summary.Severity.Code() >= severity.Code() {
msg := fmt.Sprintf("current image with '%q vulnerable' cannot be pulled due to configured policy in 'Prevent images with vulnerability severity of %q from running.' "+ msg := fmt.Sprintf("current image with '%q vulnerable' cannot be pulled due to configured policy in 'Prevent images with vulnerability severity of %q from running.' "+
"Please contact your project administrator for help'", summary.Severity, severity) "Please contact your project administrator for help'", summary.Severity, severity)
return ierror.New(nil).WithCode(ierror.PROJECTPOLICYVIOLATION).WithMessage(msg) return errors.New(nil).WithCode(errors.PROJECTPOLICYVIOLATION).WithMessage(msg)
} }
// Print scannerPull CVE list // Print scannerPull CVE list

View File

@ -18,7 +18,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/goharbor/harbor/src/controller/repository" "github.com/goharbor/harbor/src/controller/repository"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
serror "github.com/goharbor/harbor/src/server/error" serror "github.com/goharbor/harbor/src/server/error"
"github.com/goharbor/harbor/src/server/registry/util" "github.com/goharbor/harbor/src/server/registry/util"
"net/http" "net/http"
@ -46,7 +46,7 @@ func (r *repositoryHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)
if withN { if withN {
maxEntries, err = strconv.Atoi(reqQ.Get("n")) maxEntries, err = strconv.Atoi(reqQ.Get("n"))
if err != nil || maxEntries < 0 { if err != nil || maxEntries < 0 {
err := ierror.New(err).WithCode(ierror.BadRequestCode).WithMessage("the N must be a positive int type") err := errors.New(err).WithCode(errors.BadRequestCode).WithMessage("the N must be a positive int type")
serror.SendError(w, err) serror.SendError(w, err)
return return
} }
@ -81,7 +81,7 @@ func (r *repositoryHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)
if lastEntry != "" { if lastEntry != "" {
lastEntryIndex := util.IndexString(repoNames, lastEntry) lastEntryIndex := util.IndexString(repoNames, lastEntry)
if lastEntryIndex == -1 { if lastEntryIndex == -1 {
err := ierror.New(nil).WithCode(ierror.BadRequestCode).WithMessage(fmt.Sprintf("the last: %s should be a valid repository name.", lastEntry)) err := errors.New(nil).WithCode(errors.BadRequestCode).WithMessage(fmt.Sprintf("the last: %s should be a valid repository name.", lastEntry))
serror.SendError(w, err) serror.SendError(w, err)
return return
} }

View File

@ -20,7 +20,7 @@ import (
"github.com/goharbor/harbor/src/controller/event/metadata" "github.com/goharbor/harbor/src/controller/event/metadata"
"github.com/goharbor/harbor/src/controller/repository" "github.com/goharbor/harbor/src/controller/repository"
"github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/notification" "github.com/goharbor/harbor/src/pkg/notification"
"github.com/goharbor/harbor/src/pkg/registry" "github.com/goharbor/harbor/src/pkg/registry"
serror "github.com/goharbor/harbor/src/server/error" serror "github.com/goharbor/harbor/src/server/error"
@ -76,7 +76,7 @@ func deleteManifest(w http.ResponseWriter, req *http.Request) {
if _, err := digest.Parse(reference); err != nil { if _, err := digest.Parse(reference); err != nil {
switch err { switch err {
case digest.ErrDigestInvalidFormat: case digest.ErrDigestInvalidFormat:
serror.SendError(w, ierror.New(nil).WithCode(ierror.DIGESTINVALID). serror.SendError(w, errors.New(nil).WithCode(errors.DIGESTINVALID).
WithMessage(digest.ErrDigestInvalidFormat.Error())) WithMessage(digest.ErrDigestInvalidFormat.Error()))
return return
} }

View File

@ -24,7 +24,7 @@ import (
"github.com/goharbor/harbor/src/controller/artifact" "github.com/goharbor/harbor/src/controller/artifact"
"github.com/goharbor/harbor/src/controller/repository" "github.com/goharbor/harbor/src/controller/repository"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
arttesting "github.com/goharbor/harbor/src/testing/controller/artifact" arttesting "github.com/goharbor/harbor/src/testing/controller/artifact"
repotesting "github.com/goharbor/harbor/src/testing/controller/repository" repotesting "github.com/goharbor/harbor/src/testing/controller/repository"
"github.com/goharbor/harbor/src/testing/mock" "github.com/goharbor/harbor/src/testing/mock"
@ -68,7 +68,7 @@ func (m *manifestTestSuite) TestGetManifest() {
req := httptest.NewRequest(http.MethodGet, "/v2/library/hello-world/manifests/latest", nil) req := httptest.NewRequest(http.MethodGet, "/v2/library/hello-world/manifests/latest", nil)
w := &httptest.ResponseRecorder{} w := &httptest.ResponseRecorder{}
mock.OnAnything(m.artCtl, "GetByReference").Return(nil, ierror.New(nil).WithCode(ierror.NotFoundCode)) mock.OnAnything(m.artCtl, "GetByReference").Return(nil, errors.New(nil).WithCode(errors.NotFoundCode))
getManifest(w, req) getManifest(w, req)
m.Equal(http.StatusNotFound, w.Code) m.Equal(http.StatusNotFound, w.Code)
@ -100,7 +100,7 @@ func (m *manifestTestSuite) TestDeleteManifest() {
req := httptest.NewRequest(http.MethodDelete, "/v2/library/hello-world/manifests/latest", nil) req := httptest.NewRequest(http.MethodDelete, "/v2/library/hello-world/manifests/latest", nil)
w := &httptest.ResponseRecorder{} w := &httptest.ResponseRecorder{}
mock.OnAnything(m.artCtl, "GetByReference").Return(nil, ierror.New(nil).WithCode(ierror.NotFoundCode)) mock.OnAnything(m.artCtl, "GetByReference").Return(nil, errors.New(nil).WithCode(errors.NotFoundCode))
deleteManifest(w, req) deleteManifest(w, req)
m.Equal(http.StatusBadRequest, w.Code) m.Equal(http.StatusBadRequest, w.Code)

View File

@ -19,7 +19,7 @@ import (
"fmt" "fmt"
"github.com/goharbor/harbor/src/controller/repository" "github.com/goharbor/harbor/src/controller/repository"
"github.com/goharbor/harbor/src/controller/tag" "github.com/goharbor/harbor/src/controller/tag"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
serror "github.com/goharbor/harbor/src/server/error" serror "github.com/goharbor/harbor/src/server/error"
"github.com/goharbor/harbor/src/server/registry/util" "github.com/goharbor/harbor/src/server/registry/util"
@ -64,7 +64,7 @@ func (t *tagHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if withN { if withN {
maxEntries, err = strconv.Atoi(reqQ.Get("n")) maxEntries, err = strconv.Atoi(reqQ.Get("n"))
if err != nil || maxEntries < 0 { if err != nil || maxEntries < 0 {
err := ierror.New(err).WithCode(ierror.BadRequestCode).WithMessage("the N must be a positive int type") err := errors.New(err).WithCode(errors.BadRequestCode).WithMessage("the N must be a positive int type")
serror.SendError(w, err) serror.SendError(w, err)
return return
} }
@ -110,7 +110,7 @@ func (t *tagHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if lastEntry != "" { if lastEntry != "" {
lastEntryIndex := util.IndexString(tagNames, lastEntry) lastEntryIndex := util.IndexString(tagNames, lastEntry)
if lastEntryIndex == -1 { if lastEntryIndex == -1 {
err := ierror.New(nil).WithCode(ierror.BadRequestCode).WithMessage(fmt.Sprintf("the last: %s should be a valid tag name.", lastEntry)) err := errors.New(nil).WithCode(errors.BadRequestCode).WithMessage(fmt.Sprintf("the last: %s should be a valid tag name.", lastEntry))
serror.SendError(w, err) serror.SendError(w, err)
return return
} }

View File

@ -33,7 +33,7 @@ import (
"github.com/goharbor/harbor/src/controller/repository" "github.com/goharbor/harbor/src/controller/repository"
"github.com/goharbor/harbor/src/controller/scan" "github.com/goharbor/harbor/src/controller/scan"
"github.com/goharbor/harbor/src/controller/tag" "github.com/goharbor/harbor/src/controller/tag"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/server/v2.0/handler/assembler" "github.com/goharbor/harbor/src/server/v2.0/handler/assembler"
"github.com/goharbor/harbor/src/server/v2.0/handler/model" "github.com/goharbor/harbor/src/server/v2.0/handler/model"
"github.com/goharbor/harbor/src/server/v2.0/models" "github.com/goharbor/harbor/src/server/v2.0/models"
@ -181,7 +181,7 @@ func (a *artifactAPI) CopyArtifact(ctx context.Context, params operation.CopyArt
func parse(s string) (string, string, error) { func parse(s string) (string, string, error) {
matches := reference.ReferenceRegexp.FindStringSubmatch(s) matches := reference.ReferenceRegexp.FindStringSubmatch(s)
if matches == nil { if matches == nil {
return "", "", ierror.New(nil).WithCode(ierror.BadRequestCode). return "", "", errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("invalid input: %s", s) WithMessage("invalid input: %s", s)
} }
repository := matches[1] repository := matches[1]
@ -189,7 +189,7 @@ func parse(s string) (string, string, error) {
if matches[3] != "" { if matches[3] != "" {
_, err := digest.Parse(matches[3]) _, err := digest.Parse(matches[3])
if err != nil { if err != nil {
return "", "", ierror.New(nil).WithCode(ierror.BadRequestCode). return "", "", errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("invalid input: %s", s) WithMessage("invalid input: %s", s)
} }
reference = matches[3] reference = matches[3]
@ -248,7 +248,7 @@ func (a *artifactAPI) DeleteTag(ctx context.Context, params operation.DeleteTagP
} }
// the tag not found // the tag not found
if id == 0 { if id == 0 {
err = ierror.New(nil).WithCode(ierror.NotFoundCode).WithMessage( err = errors.New(nil).WithCode(errors.NotFoundCode).WithMessage(
"tag %s attached to artifact %d not found", params.TagName, artifact.ID) "tag %s attached to artifact %d not found", params.TagName, artifact.ID)
return a.SendError(ctx, err) return a.SendError(ctx, err)
} }

View File

@ -2,12 +2,11 @@ package handler
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"github.com/go-openapi/runtime/middleware" "github.com/go-openapi/runtime/middleware"
"github.com/goharbor/harbor/src/common/rbac" "github.com/goharbor/harbor/src/common/rbac"
"github.com/goharbor/harbor/src/common/security" "github.com/goharbor/harbor/src/common/security"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"github.com/goharbor/harbor/src/pkg/audit" "github.com/goharbor/harbor/src/pkg/audit"
"github.com/goharbor/harbor/src/server/v2.0/models" "github.com/goharbor/harbor/src/server/v2.0/models"
@ -29,10 +28,10 @@ type auditlogAPI struct {
func (a *auditlogAPI) ListAuditLogs(ctx context.Context, params auditlog.ListAuditLogsParams) middleware.Responder { func (a *auditlogAPI) ListAuditLogs(ctx context.Context, params auditlog.ListAuditLogsParams) middleware.Responder {
secCtx, ok := security.FromContext(ctx) secCtx, ok := security.FromContext(ctx)
if !ok { if !ok {
return a.SendError(ctx, ierror.UnauthorizedError(errors.New("security context not found"))) return a.SendError(ctx, errors.UnauthorizedError(errors.New("security context not found")))
} }
if !secCtx.IsAuthenticated() { if !secCtx.IsAuthenticated() {
return a.SendError(ctx, ierror.UnauthorizedError(nil).WithMessage(secCtx.GetUsername())) return a.SendError(ctx, errors.UnauthorizedError(nil).WithMessage(secCtx.GetUsername()))
} }
query, err := a.BuildQuery(ctx, params.Q, params.Page, params.PageSize) query, err := a.BuildQuery(ctx, params.Q, params.Page, params.PageSize)
if err != nil { if err != nil {

View File

@ -18,9 +18,8 @@ package handler
import ( import (
"context" "context"
"errors"
"github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"net/url" "net/url"
"strconv" "strconv"
@ -91,25 +90,25 @@ func (b *BaseAPI) RequireProjectAccess(ctx context.Context, projectIDOrName inte
} }
secCtx, ok := security.FromContext(ctx) secCtx, ok := security.FromContext(ctx)
if !ok { if !ok {
return ierror.UnauthorizedError(errors.New("security context not found")) return errors.UnauthorizedError(errors.New("security context not found"))
} }
if !secCtx.IsAuthenticated() { if !secCtx.IsAuthenticated() {
return ierror.UnauthorizedError(nil) return errors.UnauthorizedError(nil)
} }
return ierror.ForbiddenError(nil) return errors.ForbiddenError(nil)
} }
// RequireSysAdmin checks the system admin permission according to the security context // RequireSysAdmin checks the system admin permission according to the security context
func (b *BaseAPI) RequireSysAdmin(ctx context.Context) error { func (b *BaseAPI) RequireSysAdmin(ctx context.Context) error {
secCtx, ok := security.FromContext(ctx) secCtx, ok := security.FromContext(ctx)
if !ok { if !ok {
return ierror.UnauthorizedError(errors.New("security context not found")) return errors.UnauthorizedError(errors.New("security context not found"))
} }
if !secCtx.IsAuthenticated() { if !secCtx.IsAuthenticated() {
return ierror.UnauthorizedError(nil) return errors.UnauthorizedError(nil)
} }
if !secCtx.IsSysAdmin() { if !secCtx.IsSysAdmin() {
return ierror.ForbiddenError(nil).WithMessage(secCtx.GetUsername()) return errors.ForbiddenError(nil).WithMessage(secCtx.GetUsername())
} }
return nil return nil
} }

View File

@ -22,7 +22,7 @@ import (
"github.com/goharbor/harbor/src/common/rbac" "github.com/goharbor/harbor/src/common/rbac"
"github.com/goharbor/harbor/src/controller/artifact" "github.com/goharbor/harbor/src/controller/artifact"
"github.com/goharbor/harbor/src/controller/scan" "github.com/goharbor/harbor/src/controller/scan"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
operation "github.com/goharbor/harbor/src/server/v2.0/restapi/operations/scan" operation "github.com/goharbor/harbor/src/server/v2.0/restapi/operations/scan"
) )
@ -83,7 +83,7 @@ func (s *scanAPI) GetReportLog(ctx context.Context, params operation.GetReportLo
if bytes == nil { if bytes == nil {
// Not found // Not found
return s.SendError(ctx, ierror.NotFoundError(nil).WithMessage("report with uuid %s does not exist", params.ReportID)) return s.SendError(ctx, errors.NotFoundError(nil).WithMessage("report with uuid %s does not exist", params.ReportID))
} }
return operation.NewGetReportLogOK().WithPayload(string(bytes)) return operation.NewGetReportLogOK().WithPayload(string(bytes))

View File

@ -29,7 +29,7 @@ import (
"github.com/goharbor/harbor/src/common/dao" "github.com/goharbor/harbor/src/common/dao"
"github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/models"
"github.com/goharbor/harbor/src/core/config" "github.com/goharbor/harbor/src/core/config"
ierror "github.com/goharbor/harbor/src/lib/error" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/lib/orm"
"github.com/goharbor/harbor/src/pkg/types" "github.com/goharbor/harbor/src/pkg/types"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
@ -159,7 +159,7 @@ func (suite *Suite) ExecSQL(query string, args ...interface{}) {
// IsNotFoundErr ... // IsNotFoundErr ...
func (suite *Suite) IsNotFoundErr(err error) bool { func (suite *Suite) IsNotFoundErr(err error) bool {
return suite.True(ierror.IsNotFoundErr(err)) return suite.True(errors.IsNotFoundErr(err))
} }
// AssertResourceUsage ... // AssertResourceUsage ...