GoCollections/exceptions/RuntimeException.go

90 lines
1.8 KiB
Go
Raw Normal View History

2021-05-21 10:31:49 +08:00
package exceptions
import (
2021-05-21 11:25:53 +08:00
"fmt"
2021-05-21 10:31:49 +08:00
"io"
"os"
2021-05-21 11:14:07 +08:00
"strings"
2021-05-21 10:31:49 +08:00
)
type RuntimeException struct {
message string
exceptionMessage string
stackTrace []StackTrace
2021-05-21 11:14:07 +08:00
cause Exception
2021-05-21 10:31:49 +08:00
}
2021-05-21 11:25:53 +08:00
func NewRuntimeException(message interface{}, exceptionMessage string, getStackTrace bool, cause interface{}) RuntimeException {
2021-05-21 10:31:49 +08:00
var stackTrace []StackTrace = nil
if getStackTrace {
stackTrace = GetStackTrace()
}
if len(exceptionMessage) == 0 {
exceptionMessage = "exception caused:"
}
2021-05-21 11:18:56 +08:00
var causeException Exception = nil
2021-05-21 11:25:53 +08:00
if cause != nil {
switch cause.(type) {
case Exception:
causeException = cause.(Exception)
default:
causeException = RuntimeException{
message: fmt.Sprint(cause),
exceptionMessage: "exception caused:",
}
}
2021-05-21 11:18:56 +08:00
}
2021-05-21 10:31:49 +08:00
return RuntimeException{
2021-05-21 11:25:53 +08:00
message: fmt.Sprint(message),
2021-05-21 10:31:49 +08:00
exceptionMessage: exceptionMessage,
stackTrace: stackTrace,
2021-05-21 11:18:56 +08:00
cause: causeException,
2021-05-21 10:31:49 +08:00
}
}
2021-05-21 11:14:07 +08:00
func (o RuntimeException) Cause() Exception {
return o.cause
}
2021-05-21 10:31:49 +08:00
func (o RuntimeException) Error() string {
if len(o.message) == 0 {
return "index out of bound"
} else {
return o.message
}
}
func (o RuntimeException) StackTrace() []StackTrace {
return o.stackTrace
}
func (o RuntimeException) PrintStackTrace() {
o.PrintStackTraceTo(os.Stderr)
}
func (o RuntimeException) PrintStackTraceTo(writer io.Writer) {
2021-05-21 11:14:07 +08:00
builder := strings.Builder{}
o.BuildPrintStackTrace(&builder)
bytes := []byte(builder.String())
writeBytes := 0
for writeBytes < len(bytes) {
write, err := writer.Write(bytes[writeBytes:])
if err != nil {
2021-05-21 13:31:41 +08:00
Print(err)
2021-05-21 11:14:07 +08:00
return
}
writeBytes += write
}
}
func (o RuntimeException) BuildPrintStackTrace(builder *strings.Builder) {
2021-05-21 13:31:41 +08:00
BuildStackTrace(builder, o, o.exceptionMessage)
2021-05-21 11:14:07 +08:00
if o.cause != nil {
builder.WriteString("caused by: ")
o.cause.BuildPrintStackTrace(builder)
}
2021-05-21 10:31:49 +08:00
}