From dbcc45a94361091aa3557ad6e436f5bf03387294 Mon Sep 17 00:00:00 2001 From: tursom Date: Fri, 21 May 2021 13:31:41 +0800 Subject: [PATCH] update NewRuntimeException --- exceptions/Exception.go | 44 +++++++++++++++++++++++++++++++++- exceptions/RuntimeException.go | 3 ++- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/exceptions/Exception.go b/exceptions/Exception.go index 78a39e3..484bade 100644 --- a/exceptions/Exception.go +++ b/exceptions/Exception.go @@ -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) + } +} diff --git a/exceptions/RuntimeException.go b/exceptions/RuntimeException.go index 73762f1..3184b3b 100644 --- a/exceptions/RuntimeException.go +++ b/exceptions/RuntimeException.go @@ -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)