A Beautiful Way To Deal With ERRORS in Golang HTTP Handlers

แชร์
ฝัง
  • เผยแพร่เมื่อ 27 ธ.ค. 2024

ความคิดเห็น • 72

  • @anthonygg_
    @anthonygg_  7 หลายเดือนก่อน +2

    ► 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 7 หลายเดือนก่อน +19

    This approach is absolutely appropriate because it implements the paradigm of error handling at the source 👍

  • @JeffryDegrande
    @JeffryDegrande 7 หลายเดือนก่อน +4

    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_  7 หลายเดือนก่อน +1

      Thank you

  • @devoverlord
    @devoverlord 7 หลายเดือนก่อน +7

    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_  7 หลายเดือนก่อน +4

      Yes will do that as wel. Thanks

  • @congdatt
    @congdatt 7 หลายเดือนก่อน +25

    The next vid should be: A Beautiful Way To Deal With LOGGING in Golang

    • @anthonygg_
      @anthonygg_  7 หลายเดือนก่อน +8

      Thanks good idea.

    • @mecamon
      @mecamon 7 หลายเดือนก่อน

      I approve this

  • @assaidy
    @assaidy 4 หลายเดือนก่อน

    I am learning a lot from this channel. You're giving a lot of experience for free. Thank you so much.

  • @matiasbpg
    @matiasbpg 7 หลายเดือนก่อน +1

    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.

  • @hedgehogform
    @hedgehogform 7 หลายเดือนก่อน +3

    You're the daddy of golang. Keep it GOing!! 💪💪💪💪💪

  • @patelmalavdev
    @patelmalavdev 5 หลายเดือนก่อน

    5:38 we can check for err == nil and do early return
    I am new to programming
    but we can use Make(logger ,func) to pass in the logger to make this more useful ? depending that you are using custom logger and not using slog global value
    but can we change slog output destination anywhere? or we have to route os.Err stream to some file from linux

  • @AMacedoP
    @AMacedoP 7 หลายเดือนก่อน +7

    Is there any reason why you're not using `errors.As()` to check if your error is an ApiError?

    • @anthonygg_
      @anthonygg_  7 หลายเดือนก่อน +2

      Good question. Didnt thought about that

    • @matiasbpg
      @matiasbpg 7 หลายเดือนก่อน

      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

  • @BhargavaMan
    @BhargavaMan 6 หลายเดือนก่อน

    As a typescript / nextjs dev transitioning to Go, this is GOld. Cheers!

  • @toTheMuh
    @toTheMuh 7 หลายเดือนก่อน +1

    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}'

  • @notteleen
    @notteleen 7 หลายเดือนก่อน +1

    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.

    • @elio8119
      @elio8119 3 หลายเดือนก่อน

      I confirm, you don't need to close the body in an http handler, ever.

  • @KostasOreopoulos
    @KostasOreopoulos 7 หลายเดือนก่อน

    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.

  • @janari_dev
    @janari_dev 7 หลายเดือนก่อน +1

    which theme in vs code do you use? i am searching this theme veeeery long

  • @MaksimVolkau
    @MaksimVolkau 7 หลายเดือนก่อน +3

    What VSCode ext for Rest Api calls are you using?

    • @leepowelldev
      @leepowelldev 7 หลายเดือนก่อน +3

      Looks like Thunder Client

  • @itsthesteve
    @itsthesteve 7 หลายเดือนก่อน

    Nice vid! I was working on this earlier today. Side note - some people have 2 letter names

    • @zyriab5797
      @zyriab5797 6 หลายเดือนก่อน

      There's a nice article out there about names. Some people don't even have last names, etc

  • @sidwebworks9871
    @sidwebworks9871 7 หลายเดือนก่อน

    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 🎉❤

  • @yaroslavmamykin981
    @yaroslavmamykin981 7 หลายเดือนก่อน +2

    I do wonder why `defer r.Body.Close()` is after error check for JSON)) Won't it cause troubles?

    • @anthonygg_
      @anthonygg_  7 หลายเดือนก่อน +1

      Why its defer 😂

    • @fulopzoltan349
      @fulopzoltan349 7 หลายเดือนก่อน

      defer means it will run AT THE END of the function call.

    • @jonathanalonso6492
      @jonathanalonso6492 7 หลายเดือนก่อน +4

      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 7 หลายเดือนก่อน

      @@anthonygg_ but if there is an invalid JSON in body then request body stream is not closed?

    • @АнтонПавлов-н2ч
      @АнтонПавлов-н2ч 7 หลายเดือนก่อน +1

      ​​​@@yaroslavmamykin981 this is actually like `finally` in try-catch clause in C-like languages. So it will execute anyway

  • @AminShahbaghi
    @AminShahbaghi 7 หลายเดือนก่อน +2

    How can I access this code?

  • @dejanduh2645
    @dejanduh2645 7 หลายเดือนก่อน +1

    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

  • @arsenidziamidchyk2972
    @arsenidziamidchyk2972 7 หลายเดือนก่อน +1

    Just curious how the request validation is done. Is it a custom implementation?

    • @anthonygg_
      @anthonygg_  7 หลายเดือนก่อน +1

      Yeah its custom. You return a map with all the errors. name: ….., email: ……

    • @arsenidziamidchyk2972
      @arsenidziamidchyk2972 7 หลายเดือนก่อน

      @@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_  7 หลายเดือนก่อน

      @@arsenidziamidchyk2972 if len(email) …. Just custome logic

    • @arsenidziamidchyk2972
      @arsenidziamidchyk2972 7 หลายเดือนก่อน

      @@anthonygg_ Oh got it, thank you!

  • @richardmetzler7119
    @richardmetzler7119 7 หลายเดือนก่อน +2

    The Make() function is absolutely useful, but I wish you would name it differently.

    • @anthonygg_
      @anthonygg_  7 หลายเดือนก่อน +1

      MakeHandler

  • @eaigodoi
    @eaigodoi 7 หลายเดือนก่อน

    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?

  • @mozhago8280
    @mozhago8280 7 หลายเดือนก่อน

    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

  • @alexei4253
    @alexei4253 7 หลายเดือนก่อน +14

    This is the reason why I use Fiber instead of standard library or Gin.

    • @mohamedmacow3610
      @mohamedmacow3610 7 หลายเดือนก่อน +1

      U can do the same in Gin tho

    • @TronkyWonk
      @TronkyWonk 7 หลายเดือนก่อน

      @@mohamedmacow3610exactly. I do the same in Gin all the time.

    • @iCrimzon
      @iCrimzon 7 หลายเดือนก่อน +2

      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 7 หลายเดือนก่อน

      ​@@mohamedmacow3610 fiber more good docs and ui in docs and in core it's convenient than the other

    • @robertsimplerino
      @robertsimplerino 7 หลายเดือนก่อน

      @@iCrimzon not true about fasthttp-based frameworks

  • @konradpiotrowski9549
    @konradpiotrowski9549 7 หลายเดือนก่อน

    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 7 หลายเดือนก่อน +2

      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 7 หลายเดือนก่อน

      @@zacharybrown9842 Awesome, thank you man!:)

  • @hassanad94
    @hassanad94 7 หลายเดือนก่อน

    What happens if i dont close r.Body?

  • @RandomShowerThoughts
    @RandomShowerThoughts 7 หลายเดือนก่อน

    This is pretty clean

  • @kevinkkirimii
    @kevinkkirimii 7 หลายเดือนก่อน

    strange, I am doing this without having the handler throw an error. I guess its all about preference.

  • @ebriussenex9850
    @ebriussenex9850 7 หลายเดือนก่อน +2

    your ob'ekt instead of object sounds like ... a music to my russian ears ))

  • @rampandey191
    @rampandey191 7 หลายเดือนก่อน +1

    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 7 หลายเดือนก่อน +1

      Yes ur using panics

    • @rampandey191
      @rampandey191 7 หลายเดือนก่อน

      @@mohamedmacow3610 could you elaborate why that is a problem?

    • @fernandoacorreia
      @fernandoacorreia 6 หลายเดือนก่อน

      I believe he means that panic is not meant to be used for flow control.

  • @demmidemmi
    @demmidemmi 7 หลายเดือนก่อน

    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.

  • @heitorfreitas3662
    @heitorfreitas3662 7 หลายเดือนก่อน

    GOat

  • @OwNeDGr
    @OwNeDGr 7 หลายเดือนก่อน

    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.

    • @zyriab5797
      @zyriab5797 6 หลายเดือนก่อน

      The wheel is a perfect invention, there's no perfection in software.
      It's good to know what's going on in your code, sometimes it's worth it on the long run to not rely on stranger's code, work ethics and time.
      I think it's more of a balancing act: time vs control, in a way.

    • @matthiaslangbart9841
      @matthiaslangbart9841 6 หลายเดือนก่อน

      Yeah. Just order some pizza for your guests. Cooking is just a waste of time, right? Well, until your pizza service fails. Are you prepared for that?

    • @OwNeDGr
      @OwNeDGr 6 หลายเดือนก่อน

      ​@@matthiaslangbart9841 Yeah, of course, cook it yourself! You need to build your house, then you need to build your kitchen and your electricity. When you finish, maybe around 5-10 years if you are lucky, and if your guests are still alive, maybe you will have cooked a pizza.
      Now change the word 'guests' to 'clients' and 'pizza' to 'money'.

  • @beatrixexe
    @beatrixexe 7 หลายเดือนก่อน +1

    is there real people that make money from Golang outside of back end jobs

    • @yung5943
      @yung5943 7 หลายเดือนก่อน

      I’m interested in this too . Would love a vid on making money with these skills besides traditional employment