Go 51: Sentinel Errors & Wrapping/Unwrapping Errors with Code Examples

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Hello Everyone! Welcome to Code and Learn. We  are continuing our journey of error handling   in Go. So in tutorial 51 of our course we  will cover sentinel errors and wrapping and   unwrapping of errors. So, let's get started.  What exactly are sentinel errors? Sentinel   errors are errors that are specifically created  to indicate the occurrence of a unique event   these errors help handle certain errors in a  particular way for instance in a delete API   endpoint if no required information is found to  be deleted we simply return a success response   which means the request was successful but  how would you know if no record is found?   Sentinel errors are exported package-level  variables thus part of the public API for   the package which means that they need to be  maintained along with other parts of the code. So I just gave you an example of a delete API  endpoint and how would you know if the record   was not found in the DB one of the example  of such an error is from the standard lib   database SQL package where error no row  equal to SQL no rows in the result set   which is exported from the standard SQL  package. It indicates that no rows were   found in the database that match the query so  we can use this to check if the record was not   found and react accordingly. If err is equal to  SQL dot error no row perform the operation that   is returning 204 for successful deletion.  So that's where sentinel errors are used. Now let's discuss error wrapping  sometimes additional information   or context is needed to be added to an  error without creating a custom error   in such cases you can wrap the error  with additional information according   to go documentation an error e wraps another  error if e's type has one of the following   methods unwrap which returns error or  unwrap which returns a slice of errors. One of the very common terminology used in error  handling is error chain. An error chain refers   to a series of error that are wrapped together  it is also called the error tree so let's now   go deeper into error wrapping. In the previous  lesson we saw that you can create errors with   fmt.Errorf function the same function can be  used to wrap errors you will need to provide   the placeholder or formatting verb %w to do so  I would also like to mention in case you don't   want to wrap the error but instead just want  to add error string to the error message you   can use %v formatting verb now let's look at some  examples here in our package main first I'm going   to create an example function which returns an  error so as you can see first function is just   an example function which returns an error in any  case so we are returning an error with fmt.Errorf   original error something went wrong in the first  function now let's create the second function that   will wrap the error from first function and  return the wrapped error first let us get the   error from first function first error is equal to  call to the first error function if first error   not equal to nil let's use the %w formatting verb  to wrap the error and then we provide the first   error so this is essentially how we would  wrap errors if there's no error return nil. Let's now call the second function in  our main and let's print the error to   see what we get so here I'm just calling the  second function and printing the error let's   run our program to verify what happens go  run main.go and as you can see the error   was indeed wrapped this is the string from  the second function I just need to updated   it to say second function and this is the  string from first function let's try again   and see so failed in second function  the original or the wrapped error is   something went wrong in the first function  so that's how you would wrap errors in Go. Now there's another way of wrapping errors,  errors.Join function was introduced in the   errors package. Join returns an error that wraps  the given error provided to it. So you can provide   multiple errors to join any nil error value are  discarded join returns nil if all the values   provided in Join are nil or nil errors the error  string of the joined error is a concatenation of   strings which is obtained by calling Error  method on each of the element errors with   a new line between each string. Please note a  non-nil error returned by join implements the   unwrap returning a slice method first let us  look at how join can be used to wrap errors.   So instead of doing fmt.Errorf what I can do  is second error create a new error here with   errors.New and the error string failed in second  function now instead of doing fmt.Errorf I can do   errors.Join first error and second error now let's  run our program to verify the behavior go run   main.go and as you can see both the errors were  joined with the first error coming from the first   function and then the second error and as you can  see there's a new line between the error strings. Let's now dig into unwrapping errors the  standard lib errors package has a Unwrap   function that can be used to unwrap  errors Unwrap returns the result of   calling the Unwrap method on error if  errors type contains the Unwrap method   returning error otherwise Unwrap will return  nil the fmt.Errorf function created an error   that implemented the Unwrap method if you're  using custom errors that wrap another error   you would have to create the Unwrap method  on it please note the Unwrap function in the   errors package does not unwrap errors returned  by errors.Join or errors wrapped by errors.Join. Let's now look at the technicality from the Go  specifications if e.Unwrap returns a non-nil   error w or a slice containing w then we say e  wraps w which is the condition to satisfy for   wrapping errors it is invalid for unwrap method to  return a slice of errors containing a nil error.   A nil error return from e.Unwrap indicates that e  does not wrap any errors now let us look at some   examples for unwrapping errors let's reverse this  back to use fmt.Errorf to wrap errors as unwrap   does not unwrap any errors joined by or wrapped  by errors.Join so here we have the example in   main we are getting the wrapped error from second  function to get the internal error that is error   that was wrapped inside this error let's use the  Unrap method I'm just going to add original error   in front of it so that we can distinguishes  from the wrapped error and here we will pass   the wrapped error now let's print the inner  error let's now run our program to verify the   behaviour go run main. go and as you can see this  is the wrapped error which has error string from   both the second and the first error but when we  unwraped the inner error only has the first error   which is the original error so that's basically  how you use unwrap to unwrap wrapped error. Now let me show you how you can implement  unwrap error on your own error custom type   first I'm going to create a custom error type or  struct which has a message and the wrapped error   so here we have custom error which has message  of type string and wrapped error. Now to satisfy   the error interface let us implement the error  method here we are just returning a string or   formatted error string with the message and the  wrapped error now again to satisfy unwrapping for   our custom type we need to implement the Unwrap  method so let's do that here we have implemented   the Unwrap method we are just returning e.Wrapped  when the unwrap method is called now when you call   unwrap on custom error it will actually we call  the unwrap method implemented on the custom error   let's write a short program in main to verify the  operation first I'm going to create some function   that returns a custom error with a wrapped error  inside so as you can see some function returns   error which further returns a custom error which  has wrapped error that we created from errors.New   and provided error saying wrapped error now in  the main we are doing the same thing calling   some function getting the custom error and then  printing the error then we are also print the   inner error which should come from unwrapping  so we can do error is equal to errors.Unwrap and   provide the original error now this should call  the Unwrap method on our custom error let's run   our program to verify the behaviour again and  as you can see we were able to get the wrapped   error by calling the Unwrap function on error  which further call the Unwrap method on the   custom error function so this is basically how  you can Implement your own Unwrap method some of   the concepts could be confusing but if you try  it yourself and read the documentation which I   will provide in the description you should be  able to make sense of it let's now summarize   everything we have learned in this lesson first  we looked at Sentinel errors which indicate the   occurrence of special event in code for the  caller to react to then we looked at error   wrapping with fmt.Errorf and errors.Join we also  looked at how unwrapping works please note that   the unwrap function is rarely used as it cannot  tell you if sentinel error is present in the   error chain instead we use errors.Is and errors.As  functions from the error standard package we will   look at it in the next lesson I hope you enjoyed  the lesson if you have any questions please post   a comment under the video or reach out to our  Discord server until next time happy coding!
Info
Channel: Code & Learn
Views: 1,067
Rating: undefined out of 5
Keywords: GoLang Tutorial, Sentinel Errors, Error Wrapping, Error Unwrapping, Code Examples, Programming, Learning Go, Go Programming Language, GoLang Development, Coding Tutorial, Code Demos, GoLang Best Practices, Software Development, GoLang Educational Video, Error Handling Strategies, India
Id: 37rQlN4_xds
Channel Id: undefined
Length: 9min 56sec (596 seconds)
Published: Sun Feb 04 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.