Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log type assertion errors in golang?

I have an array of some data which I want to map in []string. I can do it in 2 ways:

a)

// someData
s := someData.([]string)

In this case, the execution would stop after listing the error on the console.

b)

// someData
s, ok := someData.([]string)

In this case, no errors would occur but s will have its zero-value


I want to log the errors in such type assertion failure cases without stopping the execution. However, when I am using type (b), I cannot see the error details.

The only solution I can think is to use reflect.TypeOf and print both the types.

Is there any other way we can get the error when using solution (b)?

like image 236
Prateek Avatar asked Jun 03 '16 08:06

Prateek


People also ask

How type assertion works in Golang?

Type assertions in Golang provide access to the exact type of variable of an interface. If already the data type is present in the interface, then it will retrieve the actual data type value held by the interface. A type assertion takes an interface value and extracts from it a value of the specified explicit type.

How do you wrap errors in go?

In Go 1.13, though, Go added support for wrapping and unwrapping errors as part of the standard library by adding the errors. Unwrap function and the %w verb for the fmt. Errorf function. In this section, you'll update your program to use the %w verb to wrap errors with more information, and you'll then use errors.

How does Golang handle API errors?

Typically the usual way to handle errors in Go is to check if the returned error value is nil. If it's equal to nil, then it means no errors occurred. Go functions can also return multiple values. In cases where a function can fail, it's a good idea to return the error status as a second return value.

How do you use try catch in Golang?

This method is also known as try-catch-finally In this method, in the try block the error-free code has been executed and if it has found some issue it will be handled in the catch block and finally block will be executed all the things at any cost.


1 Answers

You can construct the log message yourself. There's no need for explicit calls to reflect as there's a printf format string %T that produces the type.

s, ok := someData.([]string)
if !ok {
    log.Printf("got data of type %T but wanted []string", someData)
    ... handle the failure somehow
}

Without knowing the context it's hard for me to produce a useful and informational log statement, but you can adapt the idea to suit your use case.

like image 76
Paul Hankin Avatar answered Sep 30 '22 19:09

Paul Hankin