stevenferrer
stevenferrer

Reputation: 2612

Error handing in Go: When to ignore errors?

Consider the below code snippet:

m := map[string]string{
    "name": "Olivia"
}

// marshal map
b, err := json.Marshal(m)
if err != nil {
    // handle error
    ...
}

// no errrors
...

I understand that handling errors in Go is very important, but from the above example, I'm pretty sure (at least in my own experience) that the error is not gonna happen.

My question is, is it safe ignore errors in these kinds of situation?

Upvotes: 1

Views: 1302

Answers (2)

A_kat
A_kat

Reputation: 1527

Yes this is generally not so Go specific but every language specific about error handling. Something more Go related that I recommend is doing this

b, _ := json.Marshal(m)

This shows that you wont be handling the error. Altough just like any language it's not a good practice. You should log errors and handle them just like most languages

Upvotes: 0

icza
icza

Reputation: 417462

It may be safe in the above concrete example, but still omitting errors is never a good idea. You or someone else will change the code in the future and might not update the subsequent error handling (or the lack of error handling). The code might be changed to something that will fail, and there will be no mark.

The least you can do is log such errors, should they happen in the future, you will at least have some logs / marks.

A better approach is to panic for errors that shouldn't ever happen:

m := map[string]string{
    "name": "Olivia"
}

// marshal map
b, err := json.Marshal(m)
if err != nil {
    panic("never to happen")
}

See related: Check errors when calling http.ResponseWriter.Write()

Upvotes: 4

Related Questions