Handle errors in init

888 views
Skip to first unread message

Nikhilesh Susarla

unread,
Mar 9, 2022, 9:46:57 AM3/9/22
to golang-nuts
I have an init func in a package. 

Inside the init function, I have a database initialization which returns error. How can I handle that error failure incase if it fails in the init function.

Thank you
Nikhilesh

Axel Wagner

unread,
Mar 9, 2022, 10:07:27 AM3/9/22
to Nikhilesh Susarla, golang-nuts
You likely shouldn't do that in the init function, but do it from main, where you have a clearly defined error handling path.

There are ~four things you can do with an error in init:
1. Ignore it
2. Log it
3. Store it in a package-scoped variable and check that later
4. Panic
Neither of these are good options, but they are the only ones you have.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/5600c2e2-9c6d-4a24-af98-ddf52845fe24n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages