github.com/cloudwego/kitex@v0.9.0/pkg/kerrors/bizerrors_test.go (about) 1 /* 2 * Copyright 2022 CloudWeGo Authors 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 kerrors 18 19 import ( 20 "testing" 21 22 "google.golang.org/protobuf/types/known/emptypb" 23 24 "github.com/cloudwego/kitex/internal/test" 25 ) 26 27 func TestBizStatusErrors(t *testing.T) { 28 bserr := NewBizStatusError(404, "not found") 29 test.Assert(t, bserr.BizStatusCode() == 404) 30 test.Assert(t, bserr.BizMessage() == "not found") 31 bserr = NewBizStatusErrorWithExtra(502, "bad gateway", nil) 32 berr := bserr.(*BizStatusError) 33 berr.SetBizExtra("key1", "value1") 34 berr.AppendBizMessage("[tag1]") 35 test.Assert(t, bserr.BizStatusCode() == 502) 36 test.Assert(t, bserr.BizMessage() == "bad gateway [tag1]") 37 test.Assert(t, bserr.BizExtra()["key1"] == "value1") 38 test.Assert(t, bserr.Error() == "biz error: code=502, msg=bad gateway [tag1]") 39 40 var err error = bserr 41 _, ok := FromBizStatusError(err) 42 test.Assert(t, ok) 43 _, ok = FromBizStatusError(nil) 44 test.Assert(t, !ok) 45 46 // test grpc status error 47 bserr = NewGRPCBizStatusError(404, "not found") 48 test.Assert(t, bserr.BizStatusCode() == 404) 49 test.Assert(t, bserr.BizMessage() == "not found") 50 bserr = NewGRPCBizStatusErrorWithExtra(502, "bad gateway", nil) 51 gberr := bserr.(*GRPCBizStatusError) 52 gberr.SetBizExtra("key1", "value1") 53 gberr.AppendBizMessage("[tag1]") 54 st, err := gberr.GRPCStatus().WithDetails(&emptypb.Empty{}) 55 test.Assert(t, err == nil) 56 gberr.SetGRPCStatus(st) 57 test.Assert(t, bserr.BizStatusCode() == 502) 58 test.Assert(t, bserr.BizMessage() == "bad gateway [tag1]") 59 test.Assert(t, bserr.BizExtra()["key1"] == "value1") 60 test.Assert(t, bserr.Error() == "biz error: code=502, msg=bad gateway [tag1]") 61 62 err = bserr 63 _, ok = FromBizStatusError(err) 64 test.Assert(t, ok) 65 _, ok = FromBizStatusError(nil) 66 test.Assert(t, !ok) 67 }