github.com/tursom/GoCollections@v0.3.10/lang/RuntimeException.go (about) 1 /* 2 * Copyright (c) 2022 tursom. All rights reserved. 3 * Use of this source code is governed by a GPL-3 4 * license that can be found in the LICENSE file. 5 */ 6 7 package lang 8 9 import ( 10 "fmt" 11 "io" 12 "os" 13 "strings" 14 ) 15 16 type RuntimeException struct { 17 BaseObject 18 message string 19 exceptionName string 20 stackTrace []StackTrace 21 cause Exception 22 } 23 24 func NewRuntimeException(message string, config *ExceptionConfig) *RuntimeException { 25 if config == nil { 26 config = DefaultExceptionConfig() 27 } 28 29 var stackTrace []StackTrace = nil 30 if config.GetStackTrace { 31 stackTrace = GetStackTraceSkipDeep(config.SkipStack + 1) 32 } 33 34 var causeException Exception = nil 35 if config.Cause != nil { 36 switch e := config.Cause.(type) { 37 case Exception: 38 causeException = e 39 default: 40 causeException = NewPackageException(config.Cause, DefaultExceptionConfig(). 41 SetGetStackTrace(false)) 42 } 43 } 44 45 exceptionName := "github.com.tursom.GoCollections.exceptions.RuntimeException" 46 if len(config.ExceptionName) != 0 { 47 exceptionName = config.ExceptionName 48 } 49 50 return &RuntimeException{ 51 BaseObject: NewBaseObject(), 52 message: message, 53 stackTrace: stackTrace, 54 cause: causeException, 55 exceptionName: exceptionName, 56 } 57 } 58 59 func (o *RuntimeException) Cause() Exception { 60 return o.cause 61 } 62 63 func (o *RuntimeException) Error() string { 64 message := o.message 65 if len(message) == 0 { 66 if o.cause != nil { 67 message = fmt.Sprintf("%s: %s", o.Name(), o.cause.Error()) 68 } else { 69 message = o.Name() 70 } 71 } else { 72 message = fmt.Sprintf("%s: %s", o.Name(), message) 73 } 74 return message 75 } 76 77 func (o *RuntimeException) Message() string { 78 return o.message 79 } 80 81 func (o *RuntimeException) Name() string { 82 return o.exceptionName 83 } 84 85 func (o *RuntimeException) StackTrace() []StackTrace { 86 return o.stackTrace 87 } 88 89 func (o *RuntimeException) PrintStackTrace() { 90 o.PrintStackTraceTo(os.Stderr) 91 } 92 93 func (o *RuntimeException) PrintStackTraceTo(writer io.Writer) { 94 builder := strings.Builder{} 95 o.BuildPrintStackTrace(&builder) 96 bytes := []byte(builder.String()) 97 writeBytes := 0 98 for writeBytes < len(bytes) { 99 write, err := writer.Write(bytes[writeBytes:]) 100 if err != nil { 101 Print(err) 102 return 103 } 104 writeBytes += write 105 } 106 } 107 108 func (o *RuntimeException) BuildPrintStackTrace(builder *strings.Builder) { 109 BuildStackTrace(builder, o) 110 if o.cause != nil { 111 builder.WriteString("caused by: ") 112 o.cause.BuildPrintStackTrace(builder) 113 } 114 }