Merge pull request #11347 from heww/refactor-errors

Refactor errors
This commit is contained in:
He Weiwei 2020-03-30 13:06:07 +08:00 committed by GitHub
commit fbae9f0c25
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
75 changed files with 409 additions and 589 deletions

View File

@ -17,7 +17,7 @@ package artifact
import (
"container/list"
"context"
"errors"
stderrors "errors"
"fmt"
"strings"
"time"
@ -34,7 +34,7 @@ import (
"github.com/goharbor/harbor/src/controller/event/metadata"
"github.com/goharbor/harbor/src/controller/tag"
"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/q"
"github.com/goharbor/harbor/src/pkg/artifact"
@ -59,10 +59,10 @@ var (
var (
// ErrBreak error to break walk
ErrBreak = errors.New("break")
ErrBreak = stderrors.New("break")
// 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
@ -164,7 +164,7 @@ func (c *controller) ensureArtifact(ctx context.Context, repository, digest stri
}
// 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
}
@ -196,7 +196,7 @@ func (c *controller) ensureArtifact(ctx context.Context, repository, digest stri
id, err := c.artMgr.Create(ctx, artifact)
if err != nil {
// if got conflict error, try to get the artifact again
if ierror.IsConflictErr(err) {
if errors.IsConflictErr(err) {
var e error
artifact, e = c.artMgr.GetByDigest(ctx, repository, digest)
if e != nil {
@ -208,7 +208,7 @@ func (c *controller) ensureArtifact(ctx context.Context, repository, digest stri
created = true
artifact.ID = id
return nil
})(ctx); err != nil && !ierror.IsConflictErr(err) {
})(ctx); err != nil && !errors.IsConflictErr(err) {
return false, nil, err
}
@ -272,7 +272,7 @@ func (c *controller) getByTag(ctx context.Context, repository, tag string, optio
return nil, err
}
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)
}
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})
if err != nil {
// 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 err
@ -309,7 +309,7 @@ func (c *controller) deleteDeeply(ctx context.Context, id int64, isRoot bool) er
if len(parents) > 0 {
// the root artifact is referenced by other artifacts
if isRoot {
return ierror.New(nil).WithCode(ierror.ViolateForeignKeyConstraintCode).
return errors.New(nil).WithCode(errors.ViolateForeignKeyConstraintCode).
WithMessage("the deleting artifact is referenced by others")
}
// 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 {
// delete reference
if err = c.artMgr.DeleteReference(ctx, reference.ID); err != nil &&
!ierror.IsErr(err, ierror.NotFoundCode) {
!errors.IsErr(err, errors.NotFoundCode) {
return err
}
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
if err = c.artMgr.Delete(ctx, art.ID); err != nil {
// the child artifact doesn't exist, skip
if !isRoot && ierror.IsErr(err, ierror.NotFoundCode) {
if !isRoot && errors.IsErr(err, errors.NotFoundCode) {
return nil
}
return err
@ -372,7 +372,7 @@ func (c *controller) deleteDeeply(ctx context.Context, id int64, isRoot bool) er
Digest: art.Digest,
})
return err
})(ctx); err != nil && !ierror.IsErr(err, ierror.ConflictCode) {
})(ctx); err != nil && !errors.IsErr(err, errors.ConflictCode) {
return err
}
@ -419,13 +419,13 @@ func (c *controller) copyDeeply(ctx context.Context, srcRepo, reference, dstRepo
if err == nil {
// return conflict error if the root parent artifact already exists under the destination repository
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)
}
// the child artifact already under the destination repository, skip
return dstArt.ID, nil
}
if !ierror.IsErr(err, ierror.NotFoundCode) {
if !errors.IsErr(err, errors.NotFoundCode) {
return 0, err
}

View File

@ -22,7 +22,7 @@ import (
"github.com/goharbor/harbor/src/common/models"
"github.com/goharbor/harbor/src/controller/tag"
"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/q"
"github.com/goharbor/harbor/src/pkg/artifact"
@ -148,7 +148,7 @@ func (c *controllerTestSuite) TestEnsureArtifact() {
c.repoMgr.On("GetByName").Return(&models.RepoRecord{
ProjectID: 1,
}, 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.abstractor.On("AbstractMetadata").Return(nil)
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{
ProjectID: 1,
}, 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.abstractor.On("AbstractMetadata").Return(nil)
c.tagCtl.On("Ensure").Return(nil)
@ -236,11 +236,11 @@ func (c *controllerTestSuite) TestGetByDigest() {
c.repoMgr.On("GetByName").Return(&models.RepoRecord{
RepositoryID: 1,
}, 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",
"sha256:418fb88ec412e340cdbef913b8ca1bbe8f9e8dc705f9617414c1f2c8db980180", nil)
c.Require().NotNil(err)
c.True(ierror.IsErr(err, ierror.NotFoundCode))
c.True(errors.IsErr(err, errors.NotFoundCode))
// reset the mock
c.SetupTest()
@ -269,7 +269,7 @@ func (c *controllerTestSuite) TestGetByTag() {
c.tagCtl.On("List").Return(nil, nil)
art, err := c.ctl.getByTag(nil, "library/hello-world", "latest", nil)
c.Require().NotNil(err)
c.True(ierror.IsErr(err, ierror.NotFoundCode))
c.True(errors.IsErr(err, errors.NotFoundCode))
// reset the mock
c.SetupTest()
@ -343,16 +343,16 @@ func (c *controllerTestSuite) TestGetByReference() {
func (c *controllerTestSuite) TestDeleteDeeply() {
// 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)
c.Require().NotNil(err)
c.Assert().True(ierror.IsErr(err, ierror.NotFoundCode))
c.Assert().True(errors.IsErr(err, errors.NotFoundCode))
// reset the mock
c.SetupTest()
// 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)
c.Require().Nil(err)
@ -414,7 +414,7 @@ func (c *controllerTestSuite) TestCopy() {
RepositoryID: 1,
Name: "library/hello-world",
}, 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{
{
Tag: model_tag.Tag{

View File

@ -17,7 +17,7 @@ package base
import (
"context"
"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/registry"
)
@ -42,7 +42,7 @@ func (m *IndexProcessor) AbstractMetadata(ctx context.Context, content []byte, a
// AbstractAddition abstracts the addition of artifact
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)
}

View File

@ -18,7 +18,7 @@ import (
"context"
"encoding/json"
"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/registry"
"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
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)
}

View File

@ -22,7 +22,7 @@ import (
"github.com/goharbor/harbor/src/common/utils/log"
ps "github.com/goharbor/harbor/src/controller/artifact/processor"
"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/chart"
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) {
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)
}

View File

@ -17,7 +17,7 @@ package chart
import (
"github.com/docker/distribution"
"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"
chartserver "github.com/goharbor/harbor/src/pkg/chart"
"github.com/goharbor/harbor/src/testing/pkg/chart"
@ -49,16 +49,16 @@ func (p *processorTestSuite) SetupTest() {
func (p *processorTestSuite) TestAbstractAddition() {
// 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}]}`
chartYaml := `{
chartYaml := `{
name:redis,
home:http://redis.io/",
sources:[
https://github.com/bitnami/bitnami-docker-redis"
],
version:3.2.5",
description:Open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.,
@ -66,15 +66,15 @@ func (p *processorTestSuite) TestAbstractAddition() {
redis,
keyvalue,
database
],
maintainers:[
{
name:bitnami-bot,
email:containers@bitnami.com"
}
],
icon:https://bitnami.com/assets/stacks/redis/img/redis-stack-220x234.png",
apiVersion:v1,

View File

@ -16,7 +16,7 @@ package processor
import (
"context"
ierror "github.com/goharbor/harbor/src/lib/error"
"github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/pkg/artifact"
"regexp"
"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) {
// 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)
}

View File

@ -20,7 +20,7 @@ import (
"github.com/docker/distribution/manifest/schema1"
"github.com/goharbor/harbor/src/common/utils/log"
"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"
)
@ -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) {
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)
}

View File

@ -15,7 +15,7 @@
package image
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/stretchr/testify/suite"
"testing"
@ -85,7 +85,7 @@ func (m *manifestV1ProcessorTestSuite) TestAbstractMetadata() {
func (m *manifestV1ProcessorTestSuite) TestAbstractAddition() {
_, 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() {

View File

@ -21,7 +21,7 @@ import (
"github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/controller/artifact/processor"
"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/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) {
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)
}
mani, _, err := m.RegCli.PullManifest(artifact.RepositoryName, artifact.Digest)

View File

@ -18,7 +18,7 @@ import (
"github.com/docker/distribution"
"github.com/docker/distribution/manifest/schema2"
"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/testing/pkg/registry"
"github.com/stretchr/testify/suite"
@ -97,7 +97,7 @@ var (
"Entrypoint": null,
"OnBuild": null,
"Labels": {
}
},
"created": "2019-01-01T01:29:27.650294696Z",
@ -138,7 +138,7 @@ func (m *manifestV2ProcessorTestSuite) SetupTest() {
func (m *manifestV2ProcessorTestSuite) TestAbstractAddition() {
// 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
artifact := &artifact.Artifact{}

View File

@ -23,7 +23,7 @@ import (
"github.com/goharbor/harbor/src/common/models"
"github.com/goharbor/harbor/src/common/utils/log"
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/pkg/blob"
)
@ -134,7 +134,7 @@ func (c *controller) Ensure(ctx context.Context, digest string, contentType stri
return blob.ID, nil
}
if !ierror.IsNotFoundErr(err) {
if !errors.IsNotFoundErr(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) {
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...)
if err != nil {
if ierror.IsNotFoundErr(err) {
if errors.IsNotFoundErr(err) {
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) {
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...)
@ -211,7 +211,7 @@ func (c *controller) Get(ctx context.Context, digest string, options ...Option)
if err != nil {
return nil, err
} 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

View File

@ -20,7 +20,7 @@ import (
"github.com/goharbor/harbor/src/common/models"
"github.com/goharbor/harbor/src/common/utils/log"
"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/scan/whitelist"
)
@ -61,7 +61,7 @@ func (c *controller) Get(ctx context.Context, projectID int64, options ...Option
return nil, err
}
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...))
@ -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) {
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)
@ -77,7 +77,7 @@ func (c *controller) GetByName(ctx context.Context, projectName string, options
return nil, err
}
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...))

View File

@ -20,7 +20,7 @@ import (
"testing"
"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/stretchr/testify/suite"
)
@ -47,14 +47,14 @@ func (suite *ControllerTestSuite) TestGetByName() {
{
p, err := c.GetByName(context.TODO(), "test", Metadata(false))
suite.Error(err)
suite.True(ierror.IsNotFoundErr(err))
suite.True(errors.IsNotFoundErr(err))
suite.Nil(p)
}
{
p, err := c.GetByName(context.TODO(), "oops", Metadata(false))
suite.Error(err)
suite.False(ierror.IsNotFoundErr(err))
suite.False(errors.IsNotFoundErr(err))
suite.Nil(p)
}
}

View File

@ -22,7 +22,7 @@ import (
"github.com/garyburd/redigo/redis"
"github.com/goharbor/harbor/src/common/utils/log"
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/pkg/quota"
"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)
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 {

View File

@ -20,7 +20,7 @@ import (
"github.com/goharbor/harbor/src/common/dao"
"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/graph-gophers/dataloader"
)
@ -70,7 +70,7 @@ func getProjectsBatchFn(ctx context.Context, keys dataloader.Keys) []*dataloader
for _, projectID := range projectIDs {
project, ok := projectsMap[projectID]
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)
}

View File

@ -22,7 +22,7 @@ import (
"github.com/goharbor/harbor/src/common/models"
"github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/controller/project"
ierror "github.com/goharbor/harbor/src/lib/error"
"github.com/goharbor/harbor/src/lib/errors"
)
const (
@ -92,7 +92,7 @@ func RefreshForProjects(ctx context.Context) error {
referenceID := ReferenceID(p.ProjectID)
_, 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 {
log.Warningf("initialize quota for project %s failed, error: %v", p.Name, err)
continue

View File

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

View File

@ -17,7 +17,7 @@ package repository
import (
"github.com/goharbor/harbor/src/common/models"
"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"
artifacttesting "github.com/goharbor/harbor/src/testing/controller/artifact"
ormtesting "github.com/goharbor/harbor/src/testing/lib/orm"
@ -68,7 +68,7 @@ func (c *controllerTestSuite) TestEnsure() {
c.SetupTest()
// 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{
ProjectID: 1,
}, nil)

View File

@ -29,7 +29,7 @@ import (
"github.com/goharbor/harbor/src/core/config"
"github.com/goharbor/harbor/src/jobservice/job"
"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/robot"
"github.com/goharbor/harbor/src/pkg/robot/model"
@ -37,11 +37,9 @@ import (
"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/scanner"
"github.com/goharbor/harbor/src/pkg/scan/errs"
"github.com/goharbor/harbor/src/pkg/scan/report"
v1 "github.com/goharbor/harbor/src/pkg/scan/rest/v1"
"github.com/google/uuid"
"github.com/pkg/errors"
)
// DefaultController is a default singleton scan API controller.
@ -168,12 +166,12 @@ func (bc *basicController) Scan(ctx context.Context, artifact *ar.Artifact, opti
// In case it does not exist
if r == nil {
return errs.WithCode(errs.PreconditionFailed, errs.Errorf("no available scanner for project: %d", artifact.ProjectID))
return errors.PreconditionFailedError(nil).WithMessage("no available scanner for project: %d", artifact.ProjectID)
}
// Check if it is disabled
if r.Disabled {
return errs.WithCode(errs.PreconditionFailed, errs.Errorf("scanner %s is disabled", r.Name))
return errors.PreconditionFailedError(nil).WithMessage("scanner %s is disabled", r.Name)
}
artifacts, scannable, err := bc.collectScanningArtifacts(ctx, r, artifact)
@ -197,7 +195,7 @@ func (bc *basicController) Scan(ctx context.Context, artifact *ar.Artifact, opti
for _, art := range artifacts {
trackID, producesMimes, err := bc.makeReportPlaceholder(ctx, r, art, options...)
if err != nil {
if ierror.IsConflictErr(err) {
if errors.IsConflictErr(err) {
errs = append(errs, err)
} else {
return err
@ -324,7 +322,7 @@ func (bc *basicController) GetReport(ctx context.Context, artifact *ar.Artifact,
}
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)
@ -333,7 +331,7 @@ func (bc *basicController) GetReport(ctx context.Context, artifact *ar.Artifact,
}
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))

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
import (
"context"
"github.com/goharbor/harbor/src/common/utils"
"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/q"
"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
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)
}
// 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()
_, err = c.Create(ctx, tag)
return err
})(ctx); err != nil && !ierror.IsConflictErr(err) {
})(ctx); err != nil && !errors.IsConflictErr(err) {
return err
}
@ -163,11 +177,11 @@ func (c *controller) Delete(ctx context.Context, id int64) (err error) {
return err
}
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)
}
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)
}
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
import (
"github.com/goharbor/harbor/src/common"
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"
pkg_artifact "github.com/goharbor/harbor/src/pkg/artifact"
"github.com/goharbor/harbor/src/pkg/tag/model/tag"
@ -157,7 +171,7 @@ func (c *controllerTestSuite) TestDeleteImmutable() {
c.tagMgr.On("Delete").Return(nil)
err := c.ctl.Delete(nil, 1)
c.Require().NotNil(err)
c.True(ierror.IsErr(err, ierror.PreconditionCode))
c.True(errors.IsErr(err, errors.PreconditionCode))
}
func (c *controllerTestSuite) TestUpdate() {

View File

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

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
import (
@ -7,7 +21,7 @@ import (
"strings"
"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/model"
)
@ -36,7 +50,7 @@ func (itr *ImmutableTagRuleAPI) Prepare() {
} else {
text += fmt.Sprintf("%d", pid)
}
itr.SendError(internal_errors.New(err).WithCode(internal_errors.BadRequestCode))
itr.SendError(errors.New(err).WithCode(errors.BadRequestCode))
return
}
itr.projectID = pid
@ -51,7 +65,7 @@ func (itr *ImmutableTagRuleAPI) Prepare() {
}
if itRule.ProjectID != itr.projectID {
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
}
}
@ -95,7 +109,7 @@ func (itr *ImmutableTagRuleAPI) Post() {
ir := &model.Metadata{}
isValid, err := itr.DecodeJSONReqAndValidate(ir)
if !isValid {
itr.SendError(internal_errors.New(err).WithCode(internal_errors.BadRequestCode))
itr.SendError(errors.New(err).WithCode(errors.BadRequestCode))
return
}
ir.ProjectID = itr.projectID
@ -111,7 +125,7 @@ func (itr *ImmutableTagRuleAPI) Post() {
func (itr *ImmutableTagRuleAPI) Delete() {
if itr.ID <= 0 {
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
}
err := itr.ctr.DeleteImmutableRule(itr.ID)
@ -125,7 +139,7 @@ func (itr *ImmutableTagRuleAPI) Delete() {
func (itr *ImmutableTagRuleAPI) Put() {
ir := &model.Metadata{}
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
}
ir.ID = itr.ID
@ -133,7 +147,7 @@ func (itr *ImmutableTagRuleAPI) Put() {
if itr.ID <= 0 {
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
}

View File

@ -24,9 +24,8 @@ import (
"github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/controller/quota"
"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/pkg/errors"
)
// InternalAPI handles request of harbor admin...
@ -104,7 +103,7 @@ func (ia *InternalAPI) SwitchQuota() {
// SyncQuota ...
func (ia *InternalAPI) SyncQuota() {
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
}

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 (
"encoding/json"
"errors"
"fmt"
"strings"
"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 ...
type Error struct {
Cause error `json:"-"`
@ -17,7 +39,23 @@ type Error struct {
// Error returns a human readable error.
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 ...
@ -53,14 +91,15 @@ func (errs Errors) Error() string {
}
for _, e := range errs {
var err error
switch e.(type) {
case *Error:
err = e.(*Error)
default:
err, ok := e.(*Error)
if !ok {
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)

View File

@ -12,11 +12,13 @@
// See the License for the specific language governing permissions and
// limitations under the License.
package error
package errors
import (
"errors"
"testing"
"github.com/stretchr/testify/suite"
)
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
import (
"errors"
"github.com/astaxie/beego/orm"
ierror "github.com/goharbor/harbor/src/lib/error"
"github.com/goharbor/harbor/src/lib/errors"
"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
// 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) {
e := ierror.NotFoundError(err)
e := errors.NotFoundError(err)
if len(messageFormat) > 0 {
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
// 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
if errors.As(err, &pqErr) && pqErr.Code == "23505" {
e := ierror.New(err).
WithCode(ierror.ConflictCode).
e := errors.New(err).
WithCode(errors.ConflictCode).
WithMessage(messageFormat, args...)
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
// 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
if errors.As(err, &pqErr) && pqErr.Code == "23503" {
e := ierror.New(err).
WithCode(ierror.ViolateForeignKeyConstraintCode).
e := errors.New(err).
WithCode(errors.ViolateForeignKeyConstraintCode).
WithMessage(messageFormat, args...)
return e
}

View File

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

View File

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

View File

@ -20,7 +20,7 @@ import (
"strings"
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/q"
)
@ -134,7 +134,7 @@ func (d *dao) GetByDigest(ctx context.Context, repository, digest string) (*Arti
return nil, err
}
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)
}
return artifacts[0], nil
@ -170,7 +170,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err
}
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
@ -185,7 +185,7 @@ func (d *dao) Update(ctx context.Context, artifact *Artifact, props ...string) e
return err
}
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
}
@ -228,7 +228,7 @@ func (d *dao) DeleteReference(ctx context.Context, id int64) error {
return err
}
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
}
@ -287,7 +287,7 @@ func setBaseQuery(qs beegoorm.QuerySeter, query *q.Query) (beegoorm.QuerySeter,
}
b, ok := base.(string)
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 "*"`)
}
// 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, 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"`)
}
@ -347,14 +347,14 @@ func setLabelQuery(qs beegoorm.QuerySeter, query *q.Query) (beegoorm.QuerySeter,
}
al, ok := labels.(*q.AndList)
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`)
}
var collections []string
for _, value := range al.Values {
labelID, ok := value.(int64)
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`)
}
collections = append(collections, fmt.Sprintf(`SELECT artifact_id FROM label_reference WHERE label_id=%d`, labelID))

View File

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

View File

@ -4,7 +4,7 @@ import (
"context"
"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/pkg/artifactrash/model"
)
@ -58,7 +58,7 @@ func (d *dao) Delete(ctx context.Context, id int64) (err error) {
return err
}
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
}

View File

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

View File

@ -16,7 +16,7 @@ package dao
import (
"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/q"
"github.com/goharbor/harbor/src/pkg/audit/model"
@ -121,7 +121,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err
}
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
}

View File

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

View File

@ -3,10 +3,9 @@ package dao
import (
"fmt"
"errors"
"github.com/astaxie/beego/orm"
"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"
)
@ -35,7 +34,7 @@ func (i *immutableRuleDao) CreateImmutableRule(ir *model.ImmutableRule) (int64,
id, err := o.Insert(ir)
if err != nil {
if dao.IsDupRecErr(err) {
return id, internal_errors.ConflictError(err)
return id, errors.ConflictError(err)
}
return id, err
}
@ -49,7 +48,7 @@ func (i *immutableRuleDao) UpdateImmutableRule(projectID int64, ir *model.Immuta
id, err := o.Update(ir, "TagFilter")
if err != nil {
if errors.Is(err, orm.ErrNoRows) {
return id, internal_errors.NotFoundError(err)
return id, errors.NotFoundError(err)
}
return id, err
}
@ -63,7 +62,7 @@ func (i *immutableRuleDao) ToggleImmutableRule(id int64, status bool) (int64, er
id, err := o.Update(ir, "Disabled")
if err != nil {
if errors.Is(err, orm.ErrNoRows) {
return id, internal_errors.NotFoundError(err)
return id, errors.NotFoundError(err)
}
return id, err
}
@ -77,7 +76,7 @@ func (i *immutableRuleDao) GetImmutableRule(id int64) (*model.ImmutableRule, err
err := o.Read(ir)
if err != nil {
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))
}
return nil, err

View File

@ -18,7 +18,7 @@ import (
"context"
beego_orm "github.com/astaxie/beego/orm"
"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/q"
)
@ -95,7 +95,7 @@ func (d *defaultDAO) Delete(ctx context.Context, id int64) error {
return err
}
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
}
@ -126,7 +126,7 @@ func (d *defaultDAO) CreateReference(ctx context.Context, ref *Reference) (int64
err = e
} 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 {
err = ierror.New(e).WithCode(ierror.NotFoundCode).WithMessage(e.Message)
err = errors.New(e).WithCode(errors.NotFoundCode).WithMessage(e.Message)
}
}
return id, err
@ -144,7 +144,7 @@ func (d *defaultDAO) DeleteReference(ctx context.Context, id int64) error {
return err
}
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
}

View File

@ -19,7 +19,7 @@ import (
beegoorm "github.com/astaxie/beego/orm"
common_dao "github.com/goharbor/harbor/src/common/dao"
"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/q"
artdao "github.com/goharbor/harbor/src/pkg/artifact/dao"
@ -87,7 +87,7 @@ func (l *labelDaoTestSuite) TestGet() {
// not found
_, err := l.dao.Get(l.ctx, 1000)
l.Require().NotNil(err)
l.True(ierror.IsErr(err, ierror.NotFoundCode))
l.True(errors.IsErr(err, errors.NotFoundCode))
// success
label, err := l.dao.Get(l.ctx, l.id)
@ -104,7 +104,7 @@ func (l *labelDaoTestSuite) TestCreate() {
Scope: "g",
})
l.Require().NotNil(err)
l.True(ierror.IsErr(err, ierror.ConflictCode))
l.True(errors.IsErr(err, errors.ConflictCode))
}
func (l *labelDaoTestSuite) TestDelete() {
@ -113,7 +113,7 @@ func (l *labelDaoTestSuite) TestDelete() {
// not found
err := l.dao.Delete(l.ctx, 1000)
l.Require().NotNil(err)
l.True(ierror.IsErr(err, ierror.NotFoundCode))
l.True(errors.IsErr(err, errors.NotFoundCode))
}
func (l *labelDaoTestSuite) TestListByResource() {
@ -132,7 +132,7 @@ func (l *labelDaoTestSuite) TestCreateReference() {
ArtifactID: l.artID,
})
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
_, err = l.dao.CreateReference(l.ctx, &Reference{
@ -140,7 +140,7 @@ func (l *labelDaoTestSuite) TestCreateReference() {
ArtifactID: l.artID,
})
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
_, err = l.dao.CreateReference(l.ctx, &Reference{
@ -148,7 +148,7 @@ func (l *labelDaoTestSuite) TestCreateReference() {
ArtifactID: 1000,
})
l.Require().NotNil(err)
l.True(ierror.IsErr(err, ierror.NotFoundCode))
l.True(errors.IsErr(err, errors.NotFoundCode))
}
func (l *labelDaoTestSuite) DeleteReference() {
@ -157,7 +157,7 @@ func (l *labelDaoTestSuite) DeleteReference() {
// not found
err := l.dao.DeleteReference(l.ctx, 1000)
l.Require().NotNil(err)
l.True(ierror.IsErr(err, ierror.NotFoundCode))
l.True(errors.IsErr(err, errors.NotFoundCode))
}
func (l *labelDaoTestSuite) DeleteReferences() {

View File

@ -17,7 +17,7 @@ package label
import (
"context"
"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"
"time"
)
@ -79,7 +79,7 @@ func (m *manager) RemoveFrom(ctx context.Context, labelID int64, artifactID int6
return err
}
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
}

View File

@ -17,7 +17,7 @@ package label
import (
"context"
"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/stretchr/testify/mock"
"github.com/stretchr/testify/suite"
@ -109,7 +109,7 @@ func (m *managerTestSuite) TestRemoveFrom() {
m.dao.On("DeleteReferences").Return(0, nil)
err = m.mgr.RemoveFrom(nil, 1, 1)
m.Require().NotNil(err)
m.True(ierror.IsErr(err, ierror.NotFoundCode))
m.True(errors.IsErr(err, errors.NotFoundCode))
}
func (m *managerTestSuite) TestRemoveAllFrom() {

View File

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

View File

@ -16,7 +16,7 @@ package bearer
import (
"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/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@ -43,7 +43,7 @@ func TestModify(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, server.URL, nil)
err := authorizer.Modify(req)
require.NotNil(t, err)
assert.True(t, ierror.IsErr(err, ierror.UnAuthorizedCode))
assert.True(t, errors.IsErr(err, errors.UnAuthorizedCode))
// valid credential
a = basic.NewAuthorizer("username", "password")

View File

@ -33,7 +33,7 @@ import (
commonhttp "github.com/goharbor/harbor/src/common/http"
"github.com/goharbor/harbor/src/core/config"
"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/opencontainers/go-digest"
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)
if err != nil {
if ierror.IsErr(err, ierror.NotFoundCode) {
if errors.IsErr(err, errors.NotFoundCode) {
return false, "", nil
}
return false, "", err
@ -320,7 +320,7 @@ func (c *client) DeleteManifest(repository, reference string) error {
return err
}
if !exist {
return ierror.New(nil).WithCode(ierror.NotFoundCode).
return errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("%s:%s not found", repository, reference)
}
reference = digest
@ -344,7 +344,7 @@ func (c *client) BlobExist(repository, digest string) (bool, error) {
}
resp, err := c.do(req)
if err != nil {
if ierror.IsErr(err, ierror.NotFoundCode) {
if errors.IsErr(err, errors.NotFoundCode) {
return false, nil
}
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
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")
}
}
@ -536,16 +536,16 @@ func (c *client) do(req *http.Request) (*http.Response, error) {
return nil, err
}
message := fmt.Sprintf("http status code: %d, body: %s", resp.StatusCode, string(body))
code := ierror.GeneralCode
code := errors.GeneralCode
switch resp.StatusCode {
case http.StatusUnauthorized:
code = ierror.UnAuthorizedCode
code = errors.UnAuthorizedCode
case http.StatusForbidden:
code = ierror.ForbiddenCode
code = errors.ForbiddenCode
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)
}
return resp, nil

View File

@ -18,7 +18,7 @@ import (
"context"
o "github.com/astaxie/beego/orm"
"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/q"
"time"
@ -115,7 +115,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err
}
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
}
@ -130,7 +130,7 @@ func (d *dao) Update(ctx context.Context, repository *models.RepoRecord, props .
return err
}
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
}
@ -149,7 +149,7 @@ func (d *dao) AddPullCount(ctx context.Context, id int64) error {
return err
}
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

View File

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

View File

@ -17,7 +17,7 @@ package repository
import (
"context"
"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/pkg/repository/dao"
)
@ -82,7 +82,7 @@ func (m *manager) GetByName(ctx context.Context, name string) (repository *model
return nil, err
}
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)
}
return repositories[0], nil

View File

@ -1,132 +0,0 @@
// 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 errs
import (
"encoding/json"
"fmt"
)
const (
// Common error code
Common uint16 = 10000
// Conflict error code
Conflict uint16 = 10409
// PreconditionFailed error code
PreconditionFailed uint16 = 10412
)
// codeTexts behaviors as a hash map to look for the text for the given error code.
func codeTexts(code uint16) string {
switch code {
case Common:
return "common"
case Conflict:
return "conflict"
case PreconditionFailed:
return "Precondition failed"
default:
return "unknown"
}
}
// Error with code
type Error struct {
// Code of error
Code uint16 `json:"code"`
// Code represented by meaningful text
TextCode string `json:"text_code"`
// Message of error
Message string `json:"message"`
// Cause for error
Cause error `json:"cause"`
}
// Error message
func (e *Error) Error() string {
emsg := fmt.Sprintf("error: %d(%s) : %s", e.Code, e.TextCode, e.Message)
if e.Cause != nil {
emsg = fmt.Sprintf("%s : cause: %s", emsg, e.Cause.Error())
}
return emsg
}
// String outputs the error with well-formatted string.
func (e *Error) String() string {
bytes, err := json.Marshal(e)
if err != nil {
// Fallback to normal string
return e.Error()
}
return string(bytes)
}
// New common error.
func New(message string) error {
return &Error{
Code: Common,
TextCode: codeTexts(Common),
Message: message,
}
}
// Wrap error with message.
func Wrap(err error, message string) error {
return &Error{
Code: Common,
TextCode: codeTexts(Common),
Message: message,
Cause: err,
}
}
// Errorf new a message with the specified format and arguments
func Errorf(format string, args ...interface{}) error {
return &Error{
Code: Common,
TextCode: codeTexts(Common),
Message: fmt.Sprintf(format, args...),
}
}
// WithCode sets specified code for the error
func WithCode(code uint16, err error) error {
if err == nil {
return err
}
e, ok := err.(*Error)
if !ok {
return err
}
e.Code = code
e.TextCode = codeTexts(code)
return e
}
// AsError checks if the given error has the given code
func AsError(err error, code uint16) bool {
if err == nil {
return false
}
e, ok := err.(*Error)
return ok && e.Code == code
}

View File

@ -1,118 +0,0 @@
// 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 errs
import (
"encoding/json"
"strings"
"testing"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
)
// ErrorSuite is a test suite for testing Error.
type ErrorSuite struct {
suite.Suite
}
// TestError is the entry point of ErrorSuite.
func TestError(t *testing.T) {
suite.Run(t, &ErrorSuite{})
}
// TestErrorNew ...
func (suite *ErrorSuite) TestErrorNew() {
err := New("error-testing")
require.Error(suite.T(), err)
suite.Equal(true, AsError(err, Common))
suite.Condition(func() (success bool) {
return -1 != strings.Index(err.Error(), "error-testing")
})
suite.Condition(func() (success bool) {
success = strings.Contains(err.Error(), codeTexts(Common))
return
})
}
// TestErrorWrap ...
func (suite *ErrorSuite) TestErrorWrap() {
err := errors.New("error-stack")
e := Wrap(err, "wrap-message")
require.Error(suite.T(), e)
suite.Equal(true, AsError(e, Common))
suite.Condition(func() (success bool) {
success = -1 != strings.Index(e.Error(), "error-stack")
return
})
suite.Condition(func() (success bool) {
success = -1 != strings.Index(e.Error(), "wrap-message")
return
})
suite.Condition(func() (success bool) {
success = strings.Contains(e.Error(), codeTexts(Common))
return
})
}
// TestErrorErrorf ...
func (suite *ErrorSuite) TestErrorErrorf() {
err := Errorf("a=%d", 1000)
require.Error(suite.T(), err)
suite.Equal(true, AsError(err, Common))
suite.Condition(func() (success bool) {
success = strings.Contains(err.Error(), "a=1000")
return
})
suite.Condition(func() (success bool) {
success = strings.Contains(err.Error(), codeTexts(Common))
return
})
}
// TestErrorString ...
func (suite *ErrorSuite) TestErrorString() {
err := New("well-formatted-error")
require.Error(suite.T(), err)
str := err.(*Error).String()
require.Condition(suite.T(), func() (success bool) {
success = len(str) > 0
return
})
e := &Error{}
er := json.Unmarshal([]byte(str), e)
suite.NoError(er)
suite.Equal(e.Message, "well-formatted-error")
}
// TestErrorWithCode ...
func (suite *ErrorSuite) TestErrorWithCode() {
err := New("error-with-code")
require.Error(suite.T(), err)
err = WithCode(Conflict, err)
require.Error(suite.T(), err)
suite.Equal(true, AsError(err, Conflict))
suite.Condition(func() (success bool) {
success = strings.Contains(err.Error(), codeTexts(Conflict))
return
})
}

View File

@ -18,12 +18,11 @@ import (
"time"
"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/pkg/scan/all"
"github.com/goharbor/harbor/src/pkg/scan/dao/scan"
"github.com/google/uuid"
"github.com/pkg/errors"
)
const (
@ -80,7 +79,7 @@ func (bm *basicManager) Create(r *scan.Report) (string, error) {
// Status conflict
if theCopy.StartTime.Add(reportTimeout).After(time.Now()) {
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 (
"context"
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/q"
"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
}
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
}
@ -139,7 +139,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err
}
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
}

View File

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

View File

@ -15,13 +15,12 @@
package native
import (
"errors"
"fmt"
"github.com/goharbor/harbor/src/common/utils"
"github.com/goharbor/harbor/src/common/utils/log"
"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"
adp "github.com/goharbor/harbor/src/replication/adapter"
"github.com/goharbor/harbor/src/replication/filter"
@ -237,7 +236,7 @@ func (a *Adapter) PingSimple() error {
if err == 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 err

View File

@ -15,31 +15,30 @@
package error
import (
"errors"
"fmt"
openapi "github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/middleware"
commonhttp "github.com/goharbor/harbor/src/common/http"
"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"
"strings"
)
var (
codeMap = map[string]int{
ierror.BadRequestCode: http.StatusBadRequest,
ierror.DIGESTINVALID: http.StatusBadRequest,
ierror.UnAuthorizedCode: http.StatusUnauthorized,
ierror.ForbiddenCode: http.StatusForbidden,
ierror.DENIED: http.StatusForbidden,
ierror.NotFoundCode: http.StatusNotFound,
ierror.ConflictCode: http.StatusConflict,
ierror.PreconditionCode: http.StatusPreconditionFailed,
ierror.ViolateForeignKeyConstraintCode: http.StatusPreconditionFailed,
ierror.PROJECTPOLICYVIOLATION: http.StatusPreconditionFailed,
ierror.GeneralCode: http.StatusInternalServerError,
errors.BadRequestCode: http.StatusBadRequest,
errors.DIGESTINVALID: http.StatusBadRequest,
errors.UnAuthorizedCode: http.StatusUnauthorized,
errors.ForbiddenCode: http.StatusForbidden,
errors.DENIED: http.StatusForbidden,
errors.NotFoundCode: http.StatusNotFound,
errors.ConflictCode: http.StatusConflict,
errors.PreconditionCode: http.StatusPreconditionFailed,
errors.ViolateForeignKeyConstraintCode: http.StatusPreconditionFailed,
errors.PROJECTPOLICYVIOLATION: http.StatusPreconditionFailed,
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
if statusCode >= http.StatusInternalServerError {
log.Error(errPayload)
err = ierror.New(nil).WithCode(ierror.GeneralCode).WithMessage("internal server error")
errPayload = ierror.NewErrs(err).Error()
err = errors.New(nil).WithCode(errors.GeneralCode).WithMessage("internal server error")
errPayload = errors.NewErrs(err).Error()
} else {
// only log the error whose status code < 500 when debugging to avoid log flooding
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.
code = int(openAPIErr.Code())
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 {
// make sure the legacy error format is align with the new one
code = legacyErr.Code
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 {
code = codeMap[ierror.ErrCode(err)]
code = codeMap[errors.ErrCode(err)]
}
if code == 0 {
code = http.StatusInternalServerError
}
return code, ierror.NewErrs(err).Error()
return code, errors.NewErrs(err).Error()
}
var _ middleware.Responder = &ErrResponder{}

View File

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

View File

@ -23,7 +23,7 @@ import (
"github.com/goharbor/harbor/src/common/utils/log"
"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"
"github.com/goharbor/harbor/src/server/middleware"
"github.com/opencontainers/go-digest"
@ -59,7 +59,7 @@ func Middleware() func(http.Handler) http.Handler {
repo := m[middleware.RepositorySubexp]
pn, err := projectNameFromRepo(repo)
if err != nil {
serror.SendError(rw, ierror.BadRequestError(err))
serror.SendError(rw, errors.BadRequestError(err))
return
}
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
bmp, err := projectNameFromRepo(bmr)
if err != nil {
serror.SendError(rw, ierror.BadRequestError(err))
serror.SendError(rw, errors.BadRequestError(err))
return
}
art.BlobMountDigest = m[blobMountDigest]

View File

@ -34,7 +34,7 @@ import (
"github.com/goharbor/harbor/src/common/utils/log"
"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/distribution"
"github.com/goharbor/harbor/src/server/middleware"
@ -61,9 +61,9 @@ func CopyArtifactMiddleware() func(http.Handler) http.Handler {
repository, reference, _ := distribution.ParseRef(from)
art, err := artifactController.GetByReference(ctx, repository, reference, nil)
if ierror.IsNotFoundErr(err) {
if errors.IsNotFoundErr(err) {
// 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 {
logger.Errorf("get artifact %s failed, error: %v", from, err)
return err

View File

@ -8,7 +8,7 @@ import (
"github.com/goharbor/harbor/src/common/security"
"github.com/goharbor/harbor/src/controller/project"
"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"
serror "github.com/goharbor/harbor/src/server/error"
"github.com/goharbor/harbor/src/server/middleware"
@ -35,7 +35,7 @@ func Middleware() func(http.Handler) http.Handler {
return
}
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)
return
}

View File

@ -10,7 +10,7 @@ import (
"github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/core/config"
"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"
"github.com/goharbor/harbor/src/server/middleware"
"github.com/gorilla/csrf"
@ -45,7 +45,7 @@ func attachToken(w http.ResponseWriter, r *http.Request) {
func handleError(w http.ResponseWriter, r *http.Request) {
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
}

View File

@ -1,7 +1,6 @@
package immutable
import (
"errors"
"fmt"
"net/http"
@ -10,7 +9,7 @@ import (
"github.com/goharbor/harbor/src/controller/artifact"
"github.com/goharbor/harbor/src/controller/tag"
"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"
)
@ -21,11 +20,11 @@ func Middleware() func(http.Handler) http.Handler {
if err := handlePush(req); err != nil {
var e *ErrImmutable
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)
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)
return
}

View File

@ -38,7 +38,7 @@ import (
"github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/controller/artifact"
"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/pkg/blob"
"github.com/goharbor/harbor/src/pkg/distribution"
@ -85,9 +85,9 @@ func copyArtifactResources(r *http.Request, reference, referenceID string) (type
ctx := r.Context()
art, err := artifactController.GetByReference(ctx, repository, reference, nil)
if ierror.IsNotFoundErr(err) {
if errors.IsNotFoundErr(err) {
// 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 {
logger.Errorf("get artifact %s failed, error: %v", from, err)
return nil, err

View File

@ -20,7 +20,7 @@ import (
"github.com/goharbor/harbor/src/common/utils/log"
"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"
)
@ -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})
blb, err := blobController.Get(ctx, mount)
if ierror.IsNotFoundErr(err) {
if errors.IsNotFoundErr(err) {
// mount blob not found, skip to request the resources
return nil, nil
} else if err != nil {

View File

@ -22,7 +22,7 @@ import (
"github.com/docker/distribution/manifest/schema2"
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/distribution"
"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.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()
req := httptest.NewRequest(http.MethodPut, "/v2/library/photon/manifests/2.0", nil)

View File

@ -19,7 +19,7 @@ import (
"net/http"
"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"
)
@ -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) {
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)
return
}

View File

@ -15,7 +15,6 @@
package v2auth
import (
"errors"
"fmt"
"net/http"
"sync"
@ -26,7 +25,7 @@ import (
"github.com/goharbor/harbor/src/core/config"
"github.com/goharbor/harbor/src/core/promgr"
"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"
"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
rw.Header().Set("Docker-Distribution-Api-Version", "registry/2.0")
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
}
next.ServeHTTP(rw, req)

View File

@ -25,7 +25,7 @@ import (
"github.com/goharbor/harbor/src/controller/project"
"github.com/goharbor/harbor/src/controller/scan"
"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"
v1 "github.com/goharbor/harbor/src/pkg/scan/rest/v1"
"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)
if err != nil {
if !ierror.IsNotFoundErr(err) {
if !errors.IsNotFoundErr(err) {
logger.Errorf("get artifact failed, error %v", err)
}
return err
@ -105,7 +105,7 @@ func Middleware() func(http.Handler) http.Handler {
if !ok {
// No report yet?
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)
@ -130,7 +130,7 @@ func Middleware() func(http.Handler) http.Handler {
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.' "+
"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

View File

@ -18,7 +18,7 @@ import (
"encoding/json"
"fmt"
"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"
"github.com/goharbor/harbor/src/server/registry/util"
"net/http"
@ -46,7 +46,7 @@ func (r *repositoryHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)
if withN {
maxEntries, err = strconv.Atoi(reqQ.Get("n"))
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)
return
}
@ -81,7 +81,7 @@ func (r *repositoryHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)
if lastEntry != "" {
lastEntryIndex := util.IndexString(repoNames, lastEntry)
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)
return
}

View File

@ -20,7 +20,7 @@ import (
"github.com/goharbor/harbor/src/controller/event/metadata"
"github.com/goharbor/harbor/src/controller/repository"
"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/registry"
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 {
switch err {
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()))
return
}

View File

@ -24,7 +24,7 @@ import (
"github.com/goharbor/harbor/src/controller/artifact"
"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"
repotesting "github.com/goharbor/harbor/src/testing/controller/repository"
"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)
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)
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)
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)
m.Equal(http.StatusBadRequest, w.Code)

View File

@ -19,7 +19,7 @@ import (
"fmt"
"github.com/goharbor/harbor/src/controller/repository"
"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"
serror "github.com/goharbor/harbor/src/server/error"
"github.com/goharbor/harbor/src/server/registry/util"
@ -64,7 +64,7 @@ func (t *tagHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if withN {
maxEntries, err = strconv.Atoi(reqQ.Get("n"))
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)
return
}
@ -110,7 +110,7 @@ func (t *tagHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if lastEntry != "" {
lastEntryIndex := util.IndexString(tagNames, lastEntry)
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)
return
}

View File

@ -33,7 +33,7 @@ import (
"github.com/goharbor/harbor/src/controller/repository"
"github.com/goharbor/harbor/src/controller/scan"
"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/model"
"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) {
matches := reference.ReferenceRegexp.FindStringSubmatch(s)
if matches == nil {
return "", "", ierror.New(nil).WithCode(ierror.BadRequestCode).
return "", "", errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("invalid input: %s", s)
}
repository := matches[1]
@ -189,7 +189,7 @@ func parse(s string) (string, string, error) {
if matches[3] != "" {
_, err := digest.Parse(matches[3])
if err != nil {
return "", "", ierror.New(nil).WithCode(ierror.BadRequestCode).
return "", "", errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("invalid input: %s", s)
}
reference = matches[3]
@ -248,7 +248,7 @@ func (a *artifactAPI) DeleteTag(ctx context.Context, params operation.DeleteTagP
}
// the tag not found
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)
return a.SendError(ctx, err)
}

View File

@ -2,12 +2,11 @@ package handler
import (
"context"
"errors"
"fmt"
"github.com/go-openapi/runtime/middleware"
"github.com/goharbor/harbor/src/common/rbac"
"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/pkg/audit"
"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 {
secCtx, ok := security.FromContext(ctx)
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() {
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)
if err != nil {

View File

@ -18,9 +18,8 @@ package handler
import (
"context"
"errors"
"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"
"net/url"
"strconv"
@ -91,25 +90,25 @@ func (b *BaseAPI) RequireProjectAccess(ctx context.Context, projectIDOrName inte
}
secCtx, ok := security.FromContext(ctx)
if !ok {
return ierror.UnauthorizedError(errors.New("security context not found"))
return errors.UnauthorizedError(errors.New("security context not found"))
}
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
func (b *BaseAPI) RequireSysAdmin(ctx context.Context) error {
secCtx, ok := security.FromContext(ctx)
if !ok {
return ierror.UnauthorizedError(errors.New("security context not found"))
return errors.UnauthorizedError(errors.New("security context not found"))
}
if !secCtx.IsAuthenticated() {
return ierror.UnauthorizedError(nil)
return errors.UnauthorizedError(nil)
}
if !secCtx.IsSysAdmin() {
return ierror.ForbiddenError(nil).WithMessage(secCtx.GetUsername())
return errors.ForbiddenError(nil).WithMessage(secCtx.GetUsername())
}
return nil
}

View File

@ -22,7 +22,7 @@ import (
"github.com/goharbor/harbor/src/common/rbac"
"github.com/goharbor/harbor/src/controller/artifact"
"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"
)
@ -83,7 +83,7 @@ func (s *scanAPI) GetReportLog(ctx context.Context, params operation.GetReportLo
if bytes == nil {
// 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))

View File

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