github.com/ystia/yorc/v4@v4.3.0/plugin/error.go (about) 1 // Copyright 2018 Bull S.A.S. Atos Technologies - Bull, Rue Jean Jaures, B.P.68, 78340, Les Clayes-sous-Bois, France. 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 package plugin 16 17 import ( 18 "fmt" 19 20 "github.com/pkg/errors" 21 ) 22 23 // RPCError is a wrapper dedicated to allow passing errors via RPC encoding 24 // It must be used for RPC server side in the response call method (ie plugin side actually) 25 type RPCError struct { 26 Message string 27 Stack string 28 } 29 30 type stackTracer interface { 31 StackTrace() errors.StackTrace 32 } 33 34 // This allows RPCError to implement error and display message plus stack 35 func (pErr *RPCError) Error() string { 36 return fmt.Sprintf("%s%s", pErr.Message, pErr.Stack) 37 } 38 39 // RPCError needs to be explicitly typed "nil" before casting to error 40 // https://golang.org/doc/faq#nil_error 41 func toError(pErr *RPCError) error { 42 if pErr != nil { 43 return pErr 44 } 45 46 return nil 47 } 48 49 // NewRPCError allows to instantiate a RPCError from an error builtin type 50 func NewRPCError(err error) *RPCError { 51 return &RPCError{Message: err.Error(), Stack: getStackTrace(err)} 52 } 53 54 // NewRPCErrorFromMessage allows to instantiate a RPCError from a message and variadic arguments 55 func NewRPCErrorFromMessage(m string, args ...interface{}) *RPCError { 56 return &RPCError{Message: fmt.Sprintf(m, args...)} 57 } 58 59 // Internal : getStackTrace allows to get the error extended format. 60 // Each Frame of the error's StackTrace will be printed in detail. 61 func getStackTrace(err error) string { 62 var stack string 63 if err, ok := err.(stackTracer); ok { 64 stack = fmt.Sprintf("%+v", err.StackTrace()) 65 } 66 return stack 67 }