update NewRuntimeException

This commit is contained in:
tursom 2021-05-21 13:31:41 +08:00
parent 89f1190168
commit dbcc45a943
2 changed files with 45 additions and 2 deletions

View File

@ -3,6 +3,7 @@ package exceptions
import (
"fmt"
"io"
"os"
"strings"
)
@ -15,7 +16,36 @@ type Exception interface {
BuildPrintStackTrace(builder *strings.Builder)
}
func PrintStackTrace(builder *strings.Builder, e Exception, exceptionMsg string) {
func PrintStackTraceByArray(writer io.Writer, trace []StackTrace) {
if trace == nil {
return
}
builder := &strings.Builder{}
for _, stackTrace := range trace {
stackTrace.WriteTo(builder)
}
bytes := []byte(builder.String())
writeBytes := 0
for writeBytes < len(bytes) {
write, err := writer.Write(bytes[writeBytes:])
if err != nil {
Print(err)
return
}
writeBytes += write
}
}
func BuildStackTraceByArray(builder *strings.Builder, trace []StackTrace) {
if trace == nil {
return
}
for _, stackTrace := range trace {
stackTrace.WriteTo(builder)
}
}
func BuildStackTrace(builder *strings.Builder, e Exception, exceptionMsg string) {
builder.WriteString(fmt.Sprintln(exceptionMsg, e.Error()))
if e.StackTrace() == nil {
return
@ -40,3 +70,15 @@ func Try(
}
return
}
func Print(err error) {
if err == nil {
return
}
switch err.(type) {
case Exception:
err.(Exception).PrintStackTrace()
default:
_, _ = fmt.Fprintln(os.Stderr, err)
}
}

View File

@ -73,6 +73,7 @@ func (o RuntimeException) PrintStackTraceTo(writer io.Writer) {
for writeBytes < len(bytes) {
write, err := writer.Write(bytes[writeBytes:])
if err != nil {
Print(err)
return
}
writeBytes += write
@ -80,7 +81,7 @@ func (o RuntimeException) PrintStackTraceTo(writer io.Writer) {
}
func (o RuntimeException) BuildPrintStackTrace(builder *strings.Builder) {
PrintStackTrace(builder, o, o.exceptionMessage)
BuildStackTrace(builder, o, o.exceptionMessage)
if o.cause != nil {
builder.WriteString("caused by: ")
o.cause.BuildPrintStackTrace(builder)