github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/store/d/try.go (about) 1 // Copyright 2019 Dolthub, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // This file incorporates work covered by the following copyright and 16 // permission notice: 17 // 18 // Copyright 2016 Attic Labs, Inc. All rights reserved. 19 // Licensed under the Apache License, version 2.0: 20 // http://www.apache.org/licenses/LICENSE-2.0 21 22 // Package d implements several debug, error and assertion functions used throughout Noms. 23 package d 24 25 import ( 26 "errors" 27 "fmt" 28 ) 29 30 // Assertion is an interface that provides convenient methods for asserting invariants. 31 // Methods panic if the invariant isn't met. 32 type Assertion interface { 33 NoError(err error) 34 True(b bool) 35 } 36 37 // Chk will panic if an assertion made on it fails 38 var ( 39 Chk Assertion = &panicker{} 40 ) 41 42 type panicker struct{} 43 44 func (s *panicker) NoError(err error) { 45 PanicIfError(err) 46 } 47 48 func (s *panicker) True(b bool) { 49 PanicIfFalse(b) 50 } 51 52 // Panic creates an error using format and args and wraps it in a 53 // WrappedError which can be handled using Try() and TryCatch() 54 func Panic(format string, args ...interface{}) { 55 if len(args) == 0 { 56 err := errors.New(format) 57 panic(err) 58 } 59 err := fmt.Errorf(format, args...) 60 panic(err) 61 } 62 63 // PanicIfError panics if the err given is not nil 64 func PanicIfError(err error) { 65 if err != nil { 66 panic(err) 67 } 68 } 69 70 // PanicIfTrue panics if the bool given is true 71 func PanicIfTrue(b bool) { 72 if b { 73 panic(errors.New("expected true")) 74 } 75 } 76 77 // PanicIfFalse panics if the bool given is false 78 func PanicIfFalse(b bool) { 79 if !b { 80 panic(errors.New("expected false")) 81 } 82 }