A Beautiful Way To Deal With ERRORS in Golang HTTP Handlers

  Рет қаралды 9,839

Anthony GG

Anthony GG

16 күн бұрын

Learn how to handle errors in your Golang HTTP handlers effectively. In this video, I'll show you the best practices for dealing with errors in your Golang code.
► Join my Discord community for FREE education 👉 / discord
► Full Projects, Mini courses, Resume reviews, and Coaching 👉 thetotalcoder.com
► 33% OFF on my Go + HTMX + Templ Course 👉bit.ly/3UFruxO
► Enjoy a 60% Black Friday Discount on My Golang Course 👉 fulltimegodev.com
► Follow me on Twitter 👉 / anthdm
► Follow me on GitHub 👉 github.com/anthdm

Пікірлер: 61
@anthonygg_
@anthonygg_ 15 күн бұрын
► 33% OFF on my Go + HTMX + Templ Course PRESALE bit.ly/3UFruxO ► Full Projects, Mini courses, Resume reviews, and Coaching thetotalcoder.com ► Join my Discord community for free education discord.com/invite/Ac7CWREe58 ► 60% OFF on my Golang course fulltimegodev.com Goose GitHub: github.com/pressly/goose Thanks for watching
@airbeast5671
@airbeast5671 15 күн бұрын
This approach is absolutely appropriate because it implements the paradigm of error handling at the source 👍
@congdatt
@congdatt 15 күн бұрын
The next vid should be: A Beautiful Way To Deal With LOGGING in Golang
@anthonygg_
@anthonygg_ 15 күн бұрын
Thanks good idea.
@mecamon
@mecamon 14 күн бұрын
I approve this
@JeffryDegrande
@JeffryDegrande 12 күн бұрын
This is such an elegant organization. I'm sorry, I'm stealing this :) Your Make() function translates beautifully to Echo's HTTPErrorHandler callback. Very, very useful video. Thank you so much for this Anthony
@anthonygg_
@anthonygg_ 9 күн бұрын
Thank you
@devoverlord
@devoverlord 14 күн бұрын
This is beautiful. The only thing i'd say you're missing is generating a request id per request so that if a bug report is filed either by a consumer or a user of the frontend, they can included that request id in their report and you can look up the log messages for their specific request(s).
@anthonygg_
@anthonygg_ 14 күн бұрын
Yes will do that as wel. Thanks
@hedgehogform
@hedgehogform 15 күн бұрын
You're the daddy of golang. Keep it GOing!! 💪💪💪💪💪
@sidwebworks9871
@sidwebworks9871 15 күн бұрын
I love your content and this new layout of videos where you just pick one topic and just keep the video short and concise is really good 🎉❤
@matiasbpg
@matiasbpg 14 күн бұрын
Even thought I'm not completely convinced with returning errors as a default, i see how this can be very clean, more so if you implement this useful error types.
@RandomShowerThoughts
@RandomShowerThoughts Күн бұрын
This is pretty clean
@KostasOreopoulos
@KostasOreopoulos 14 күн бұрын
The beauty of errors in golang is its open to different implementations. I always try to improve my handling and get new ideas. For now my take is the following. There are three type of errors I want to handle 1. User validation errors, or sql errors that are results of a query 2. Server errors that are expected (for example server is down) 3. Server errors that should not happen. For example Json marshal/unmarshal Which means my validation is wrong somewhere. The last 2 are internal server errors, which I want to bubble and wrap as they get to the handler, since it will create the path trace. I also might want to trigger some action (for example special log or email to the admin to handle it asap). The first one should have a fixed response for each error and will not wrap. So the error message from the origin of the error bubbles up intact. Of course there is a another issue to solve when the api is multilingual.
@richardmetzler7119
@richardmetzler7119 6 күн бұрын
The Make() function is absolutely useful, but I wish you would name it differently.
@anthonygg_
@anthonygg_ 6 күн бұрын
MakeHandler
@dejanduh2645
@dejanduh2645 2 күн бұрын
Can you make an updated API series where you build a complete JSON api with the std library router with postgres and error handeling like this? That would be awesome
@mozhago8280
@mozhago8280 13 күн бұрын
Great episode as usual, Just I have one concern what if you make the invalidJSON veridic func then u can throw away the InvalidJSONData and ur code will be very idiomatic
@eaigodoi
@eaigodoi 6 күн бұрын
Great video, thanks for share! I have one concern about return a message string sometimes and others an object, seems a little confuse. Could you comment about, please?
@AMacedoP
@AMacedoP 15 күн бұрын
Is there any reason why you're not using `errors.As()` to check if your error is an ApiError?
@anthonygg_
@anthonygg_ 15 күн бұрын
Good question. Didnt thought about that
@matiasbpg
@matiasbpg 14 күн бұрын
Agree, that even for this example is the same thing, error.As is more robust and will work if you error wrap down the function stack
@janari_dev
@janari_dev 14 күн бұрын
which theme in vs code do you use? i am searching this theme veeeery long
@notteleen
@notteleen 7 күн бұрын
Hello! I've read in the docs of body for HTTP request that it's closed automatically by a server, so it's not necessary to call defer r.Body.Close() in any HTTP handler.
@MaksimVolkau
@MaksimVolkau 15 күн бұрын
What VSCode ext for Rest Api calls are you using?
@leepowelldev
@leepowelldev 15 күн бұрын
Looks like Thunder Client
@toTheMuh
@toTheMuh 15 күн бұрын
Is there a reason why you do not use the http.Error() function of net/http package? I use it like 'if err != nil {http.Error(w, responseErr.Message, responseErr.Status) return}'
@heitorfreitas3662
@heitorfreitas3662 15 күн бұрын
GOat
@alexei4253
@alexei4253 15 күн бұрын
This is the reason why I use Fiber instead of standard library or Gin.
@mohamedmacow3610
@mohamedmacow3610 15 күн бұрын
U can do the same in Gin tho
@BryanT369
@BryanT369 14 күн бұрын
@@mohamedmacow3610exactly. I do the same in Gin all the time.
@iCrimzon
@iCrimzon 11 күн бұрын
Theres no difference between frameworks, all they do is remove boiler plate from using standard library, but liking Fiber over Gin if youre used to it is fine too
@umardev500
@umardev500 11 күн бұрын
​@@mohamedmacow3610 fiber more good docs and ui in docs and in core it's convenient than the other
@bobsimple8291
@bobsimple8291 5 күн бұрын
@@iCrimzon not true about fasthttp-based frameworks
@konradpiotrowski9549
@konradpiotrowski9549 14 күн бұрын
What is this "TC" file or something for sending requests? I see it for the first time, I am always using Postman to do these, but sometimes running one request for quick test inside VSC could be handy and I don't want to run "curl" :P
@zacharybrown9842
@zacharybrown9842 14 күн бұрын
He's running a plugin called Thunder Client, i.e. TC and you can save all your api calls in tc files. Similliar to postman but integrates nicely into the IDE
@konradpiotrowski9549
@konradpiotrowski9549 14 күн бұрын
@@zacharybrown9842 Awesome, thank you man!:)
@AminShahbaghi
@AminShahbaghi 13 күн бұрын
How can I access this code?
@ebriussenex9850
@ebriussenex9850 13 күн бұрын
your ob'ekt instead of object sounds like ... a music to my russian ears ))
@hassanad94
@hassanad94 15 күн бұрын
What happens if i dont close r.Body?
@arsenidziamidchyk2972
@arsenidziamidchyk2972 14 күн бұрын
Just curious how the request validation is done. Is it a custom implementation?
@anthonygg_
@anthonygg_ 14 күн бұрын
Yeah its custom. You return a map with all the errors. name: ….., email: ……
@arsenidziamidchyk2972
@arsenidziamidchyk2972 14 күн бұрын
@@anthonygg_ Yeah that's clear. But how do you do the validation itself? I guess you're using some schema/validation package for that
@anthonygg_
@anthonygg_ 14 күн бұрын
@@arsenidziamidchyk2972 if len(email) …. Just custome logic
@arsenidziamidchyk2972
@arsenidziamidchyk2972 14 күн бұрын
@@anthonygg_ Oh got it, thank you!
@yaroslavmamykin981
@yaroslavmamykin981 15 күн бұрын
I do wonder why `defer r.Body.Close()` is after error check for JSON)) Won't it cause troubles?
@anthonygg_
@anthonygg_ 15 күн бұрын
Why its defer 😂
@fulopzoltan349
@fulopzoltan349 15 күн бұрын
defer means it will run AT THE END of the function call.
@jonathanalonso6492
@jonathanalonso6492 15 күн бұрын
Adding the `defer` tells the compiler to run `r.Body.Close()` at the end of the function. It's a neat way to group code that is an "allocate" and "free" for the same resource, instead of having to remember to manually add the "free" (or "Close()" in this case) at the end of the function.
@yaroslavmamykin981
@yaroslavmamykin981 15 күн бұрын
@@anthonygg_ but if there is an invalid JSON in body then request body stream is not closed?
@user-yu4xm9ou4e
@user-yu4xm9ou4e 15 күн бұрын
​​​@@yaroslavmamykin981 this is actually like `finally` in try-catch clause in C-like languages. So it will execute anyway
@kevinkkirimii
@kevinkkirimii 15 күн бұрын
strange, I am doing this without having the handler throw an error. I guess its all about preference.
@demmidemmi
@demmidemmi 14 күн бұрын
Just commenting to comment. This feels really convenient but not very go like. This ads a lot of inderection and unnecessary layers when the same functions could just write directly to the response writer. Which would be much simpler and clearer and do away with two or three unnecessary layers of inderection. But this is pretty much the same discussion for the 10th time on if handlers should returns errors our write to the response.
@rampandey191
@rampandey191 15 күн бұрын
So what I currently do with the net/http library is use panic in controllers and recover it in a central error handling middleware. I can pass my custom error interface which the middleware can use to send data. Any problems with this approach?
@mohamedmacow3610
@mohamedmacow3610 15 күн бұрын
Yes ur using panics
@rampandey191
@rampandey191 15 күн бұрын
@@mohamedmacow3610 could you elaborate why that is a problem?
@beatrixexe
@beatrixexe 15 күн бұрын
is there real people that make money from Golang outside of back end jobs
@yung5943
@yung5943 15 күн бұрын
I’m interested in this too . Would love a vid on making money with these skills besides traditional employment
@OwNeDGr
@OwNeDGr 14 күн бұрын
Again we discover the wheel aye :P? Just use a framework do your job and that's all. Time is money you are not special, make it worthy.
Golang Channels Or Wait Groups? Let Me Explain.
18:32
Anthony GG
Рет қаралды 15 М.
THIS is the BEST Way to Write HTTP Services in Golang
13:53
ШЕЛБИЛАР | bayGUYS
24:45
bayGUYS
Рет қаралды 681 М.
Bro be careful where you drop the ball  #learnfromkhaby  #comedy
00:19
Khaby. Lame
Рет қаралды 19 МЛН
Не пей газировку у мамы в машине
00:28
Даша Боровик
Рет қаралды 10 МЛН
The standard library now has all you need for advanced routing in Go.
13:52
Go Pointers: When & How To Use Them Efficiently
14:09
Anthony GG
Рет қаралды 62 М.
Golang's Mocking Techniques - Kyle Yost | hatchpad Huddle
41:20
You Are WRONG About 0 Based Indexing
25:02
ThePrimeTime
Рет қаралды 187 М.
The Most Efficient Struct Configuration Pattern For Golang
11:10
This Zsh config is perhaps my favorite one yet.
17:24
Dreams of Autonomy
Рет қаралды 87 М.
How To Structure Your Golang (API) Projects!?
20:28
Anthony GG
Рет қаралды 42 М.
Function Iterators might just change the way we write loops in Go
11:35
I Reviewed The Perfect GOLANG Assignment Until This Happened
17:10
Что такое gRPC и Protobuf?
8:37
Merion Academy
Рет қаралды 36 М.
ШЕЛБИЛАР | bayGUYS
24:45
bayGUYS
Рет қаралды 681 М.