type-switch

Can we create subtypes for errors in Go?

不羁岁月 提交于 2019-12-13 02:51:02
问题 I want to create hierarchical errors in Go. Can we achieve this in Go ? For an example, I have following two errors. type Error1 struct { reason string cause error } func (error1 Error1) Error() string { if error1.cause == nil || error1.cause.Error() == "" { return fmt.Sprintf("[ERROR]: %s\n", error1.reason) } else { return fmt.Sprintf("[ERROR]: %s\nCaused By: %s\n", error1.reason, error1.cause) } } type Error2 struct { reason string cause error } func (error2 Error2) Error() string { if

How to create multi-level Error subtypes in Go

Deadly 提交于 2019-12-11 16:47:55
问题 I was trying to create sub-types of errors in GO. I've asked a question previously regarding the matter. Now I'am facing an issue with the multiple types. Following code shows the error type definitions: /* Interfaces */ type UniversalError interface { CommonError1 } type CommonError1 interface { error CommonError1() } /* Structs */ type Error1 struct { reason string } type Error2 struct { reason string } type Error3 struct { reason string } /* Interface function implementations */ func

Golang convert json with variable types to strings

你。 提交于 2019-12-11 02:14:32
问题 I am reading in json from an API response and I ran into an issue in that there are multiple data types inside the json values (strings, null, bool). In addition, some keys have values which can be either a string or null which makes reading the data into types more difficult. I want to convert everything to strings for ease of handling. I created a type switch based on googling other examples. I am wondering if this is the easiest way to do this or if I am missing a simpler approach. package