github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/internal/error_presenter/presenter.go (about)

     1  package errorpresenter
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  
     8  	"github.com/kyma-incubator/compass/components/director/pkg/apperrors"
     9  
    10  	"github.com/kyma-incubator/compass/components/director/pkg/log"
    11  
    12  	"github.com/99designs/gqlgen/graphql"
    13  	"github.com/vektah/gqlparser/v2/gqlerror"
    14  )
    15  
    16  // UUIDService missing godoc
    17  type UUIDService interface {
    18  	Generate() string
    19  }
    20  
    21  type presenter struct {
    22  	uuidService UUIDService
    23  }
    24  
    25  // NewPresenter missing godoc
    26  func NewPresenter(service UUIDService) *presenter {
    27  	return &presenter{uuidService: service}
    28  }
    29  
    30  // Do missing godoc
    31  func (p *presenter) Do(ctx context.Context, err error) *gqlerror.Error {
    32  	customErr := apperrors.Error{}
    33  	errID := p.uuidService.Generate()
    34  
    35  	if found := errors.As(err, &customErr); !found {
    36  		log.C(ctx).WithField("errorID", errID).Errorf("Unknown error: %v", err)
    37  		return newGraphqlErrorResponse(ctx, apperrors.InternalError, "Internal Server Error [errorID=%s, reason: %s]", errID, err.Error())
    38  	}
    39  
    40  	if apperrors.ErrorCode(customErr) == apperrors.InternalError {
    41  		log.C(ctx).WithField("errorID", errID).Errorf("Internal Server Error: %v", err)
    42  		return newGraphqlErrorResponse(ctx, apperrors.InternalError, "Internal Server Error [errorID=%s]", errID)
    43  	}
    44  
    45  	log.C(ctx).WithField("errorID", errID).WithError(err).Error()
    46  	return newGraphqlErrorResponse(ctx, apperrors.ErrorCode(customErr), customErr.Error())
    47  }
    48  
    49  func newGraphqlErrorResponse(ctx context.Context, errCode apperrors.ErrorType, msg string, args ...interface{}) *gqlerror.Error {
    50  	return &gqlerror.Error{
    51  		Message:    fmt.Sprintf(msg, args...),
    52  		Path:       graphql.GetFieldContext(ctx).Path(),
    53  		Extensions: map[string]interface{}{"error_code": errCode, "error": errCode.String()},
    54  	}
    55  }