viettranx / micro-clean-architecture-service-demo

A demo microservice with Clean Architecture in practice
260 stars 90 forks source link

Many type error in repository #2

Closed Nghiait123456 closed 1 year ago

Nghiait123456 commented 1 year ago

https://github.com/viettranx/micro-clean-architecture-service-demo/blob/main/services/user/repository/mysql/get_user.go#L27-L35

in this code you return 2 errors : sentinel_errors and warp error. Personally, I find returning 2 types of error codes in the same function a bit awkward for the parent function calling it in this case. I will check between sentinnel_errors and warp_error. Another thing is, warp_error will rarely be used to check for type errors of type ==, but will usually only print if there is an error to trace. Here, I have a need to check more errror types of gorms, but it is difficult to check, because it has been mapped to warp.error.

In this paragraph, I usually just return a type of Gorm's sentinel_errors to make it easiest to handle for the function call it. VD:

    func (repo *mysqlRepo) GetUserById(ctx context.Context, id int) (*entity.User, error) {
        var data entity.User

        if err := repo.db.
            Table(data.TableName()).
            Where("id = ?", id).
            First(&data).Error; err != nil {
            if err == gorm.ErrRecordNotFound {
                return nil, core.ErrNotFound
            }
            return nil, err
        }

        return &data, nil
    }

Looking forward to hearing from the author to discuss and learn more.

viettranx commented 1 year ago

Your point is good. I use this wrap for tracing and hiding some sensitive messges from the db library. If you dont wrap, you have to guarantee the callers do it, in my case, business layer.

About checking error, for integration testing, you might want to check with your specific error messages, not a dynamic/unexpected error.