mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
error: Add unwrap (#24)
Add a unwrap func helper * Unwrap if err is nil then it returns a valid value otherwise it panics
This commit is contained in:
14
xerror/xerror.go
Normal file
14
xerror/xerror.go
Normal file
@@ -0,0 +1,14 @@
|
||||
// Copyright 2021 dudaodong@gmail.com. All rights reserved.
|
||||
// Use of this source code is governed by MIT license
|
||||
|
||||
// Package xerror implements helpers for errors
|
||||
package xerror
|
||||
|
||||
// Unwrap if err is nil then it returns a valid value
|
||||
// If err is not nil, Unwrap panics with err.
|
||||
func Unwrap[T any](val T, err error) T {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return val
|
||||
}
|
||||
24
xerror/xerror_test.go
Normal file
24
xerror/xerror_test.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package xerror
|
||||
|
||||
import (
|
||||
"github.com/duke-git/lancet/internal"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUnwrap(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestUnwrap")
|
||||
assert.Equal(42, Unwrap(strconv.Atoi("42")))
|
||||
}
|
||||
|
||||
func TestUnwrapFail(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestUnwrapFail")
|
||||
|
||||
_, err := strconv.Atoi("4o2")
|
||||
defer func() {
|
||||
v := recover()
|
||||
assert.Equal(err.Error(), v.(*strconv.NumError).Error())
|
||||
}()
|
||||
|
||||
Unwrap(strconv.Atoi("4o2"))
|
||||
}
|
||||
Reference in New Issue
Block a user