as.go (632B)
1 //go:build !go1.26 2 3 package pq 4 5 import ( 6 "errors" 7 "slices" 8 ) 9 10 // As asserts that the given error is [pq.Error] and returns it, returning nil 11 // if it's not a pq.Error. 12 // 13 // It will return nil if the pq.Error is not one of the given error codes. If no 14 // codes are given it will always return the Error. 15 // 16 // This is safe to call with a nil error. 17 func As(err error, codes ...ErrorCode) *Error { 18 if err == nil { // Not strictly needed, but prevents alloc for nil errors. 19 return nil 20 } 21 pqErr := new(Error) 22 if errors.As(err, &pqErr) && (len(codes) == 0 || slices.Contains(codes, pqErr.Code)) { 23 return pqErr 24 } 25 return nil 26 }