2021-05-21 10:31:49 +08:00
|
|
|
package exceptions
|
|
|
|
|
|
|
|
import (
|
|
|
|
"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:18:56 +08:00
|
|
|
func NewRuntimeException(message, 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
|
|
|
|
switch cause.(type) {
|
|
|
|
case Exception:
|
|
|
|
causeException = cause.(Exception)
|
|
|
|
}
|
|
|
|
|
2021-05-21 10:31:49 +08:00
|
|
|
return RuntimeException{
|
|
|
|
message: message,
|
|
|
|
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 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
writeBytes += write
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (o RuntimeException) BuildPrintStackTrace(builder *strings.Builder) {
|
|
|
|
PrintStackTrace(builder, o, o.exceptionMessage)
|
|
|
|
if o.cause != nil {
|
|
|
|
builder.WriteString("caused by: ")
|
|
|
|
o.cause.BuildPrintStackTrace(builder)
|
|
|
|
}
|
2021-05-21 10:31:49 +08:00
|
|
|
}
|