github.com/openshift-online/ocm-sdk-go@v0.1.473/database/error_code.go (about)

     1  /*
     2  Copyright (c) 2021 Red Hat, Inc.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8    http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package database
    18  
    19  import (
    20  	"reflect"
    21  )
    22  
    23  // ErrorCode extracts the error code from the given error returned by a database operation. It uses
    24  // reflection to get the value of the `Code` field in order to avoid having to import the `lib/pq`
    25  // and `pgx` packages. It returns an empty string if the passed error is nil or it hasn't the `Code`
    26  // field.
    27  func ErrorCode(err error) string {
    28  	if err == nil {
    29  		return ""
    30  	}
    31  	value := reflect.ValueOf(err)
    32  	if value.Type().Kind() != reflect.Ptr {
    33  		return ""
    34  	}
    35  	elem := value.Elem()
    36  	if elem.Type().Kind() != reflect.Struct {
    37  		return ""
    38  	}
    39  	field := elem.FieldByName("Code")
    40  	if !field.IsValid() {
    41  		return ""
    42  	}
    43  	if field.Type().Kind() != reflect.String {
    44  		return ""
    45  	}
    46  	return field.String()
    47  }