Proper error handling when no entity is foundError handling in C codeCan I try/catch a warning?Proper Repository Pattern Design in PHP?Pointers vs. values in parameters and return valuesMultiple values in single-value contextHow do I handle nil return values from database?golang datastore projection query returning empty strings from a populated entityIs it idiomatic in go to handle all returned errors?Google cloud datastore + golang + embedded entitiesGolang error handling from function and caller to the terminal

constant evaluation when using differential equations.

Visa National - No Exit Stamp From France on Return to the UK

How does "Te vas a cansar" mean "You're going to get tired"?

Continuous vertical line using booktabs in tabularx table?

What does Apple mean by "This may decrease battery life"?

How does 'AND' distribute over 'OR' (Set Theory)?

During the Space Shuttle Columbia Disaster of 2003, Why Did The Flight Director Say, "Lock the doors."?

Should I ask for permission to write an expository post about someone's else research?

Tikzpicture - finish drawing a curved line for a cake slice

Why did the RAAF procure the F/A-18 despite being purpose-built for carriers?

How can I shift my job responsibilities back to programming?

Bitcoin successfully deducted on sender wallet but did not reach receiver wallet

Is there a standardised way to check fake news?

DeclareMathOperator and widearcarrow with kpfonts

Why are Gatwick's runways too close together?

PhD advisor lost funding, need advice

Multirow in tabularx?

Is there a way to unplug the Raspberry pi safely without shutting down

Was the 2019 Lion King film made through motion capture?

Who are these characters/superheroes in the posters from Chris's room in Family Guy?

What is the maximum number of PC-controlled undead?

Box of tablets, whole or broken: solution required

Can the ground attached to neutral fool a receptacle tester?

AsyncDictionary - Can you break thread safety?



Proper error handling when no entity is found


Error handling in C codeCan I try/catch a warning?Proper Repository Pattern Design in PHP?Pointers vs. values in parameters and return valuesMultiple values in single-value contextHow do I handle nil return values from database?golang datastore projection query returning empty strings from a populated entityIs it idiomatic in go to handle all returned errors?Google cloud datastore + golang + embedded entitiesGolang error handling from function and caller to the terminal






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm writing a Go application which has a database package. Now in database package there are a couple of methods which you can call for getting an entity based on some fields.



I was wondering what is the best practice for error handling in Go when no entity is found. Should I return errors in my own database package or return nil as the value?



I know google's datastore returns error when no entity is found.



Right now I'm using gorm and it also returns error when no entity is found.



I'm wondering you can simply return nil as the value instead of returning an error. Am I missing a point?










share|improve this question





















  • 1





    There is no "best practice" here. Only opinion. Do what makes sense for your application.

    – Flimzy
    Mar 27 at 11:21











  • "can simply return nil as the value instead of returning an error"? Yes, syntactically, if your return type is a pointer type, nil is a valid value for that type. As to whether you should, that's purely opinion-based.

    – Adrian
    Mar 27 at 13:19

















0















I'm writing a Go application which has a database package. Now in database package there are a couple of methods which you can call for getting an entity based on some fields.



I was wondering what is the best practice for error handling in Go when no entity is found. Should I return errors in my own database package or return nil as the value?



I know google's datastore returns error when no entity is found.



Right now I'm using gorm and it also returns error when no entity is found.



I'm wondering you can simply return nil as the value instead of returning an error. Am I missing a point?










share|improve this question





















  • 1





    There is no "best practice" here. Only opinion. Do what makes sense for your application.

    – Flimzy
    Mar 27 at 11:21











  • "can simply return nil as the value instead of returning an error"? Yes, syntactically, if your return type is a pointer type, nil is a valid value for that type. As to whether you should, that's purely opinion-based.

    – Adrian
    Mar 27 at 13:19













0












0








0








I'm writing a Go application which has a database package. Now in database package there are a couple of methods which you can call for getting an entity based on some fields.



I was wondering what is the best practice for error handling in Go when no entity is found. Should I return errors in my own database package or return nil as the value?



I know google's datastore returns error when no entity is found.



Right now I'm using gorm and it also returns error when no entity is found.



I'm wondering you can simply return nil as the value instead of returning an error. Am I missing a point?










share|improve this question
















I'm writing a Go application which has a database package. Now in database package there are a couple of methods which you can call for getting an entity based on some fields.



I was wondering what is the best practice for error handling in Go when no entity is found. Should I return errors in my own database package or return nil as the value?



I know google's datastore returns error when no entity is found.



Right now I'm using gorm and it also returns error when no entity is found.



I'm wondering you can simply return nil as the value instead of returning an error. Am I missing a point?







database go error-handling






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 8:58









Abdullah

1,0711 gold badge7 silver badges18 bronze badges




1,0711 gold badge7 silver badges18 bronze badges










asked Mar 27 at 8:32









Mohi_kMohi_k

26 bronze badges




26 bronze badges










  • 1





    There is no "best practice" here. Only opinion. Do what makes sense for your application.

    – Flimzy
    Mar 27 at 11:21











  • "can simply return nil as the value instead of returning an error"? Yes, syntactically, if your return type is a pointer type, nil is a valid value for that type. As to whether you should, that's purely opinion-based.

    – Adrian
    Mar 27 at 13:19












  • 1





    There is no "best practice" here. Only opinion. Do what makes sense for your application.

    – Flimzy
    Mar 27 at 11:21











  • "can simply return nil as the value instead of returning an error"? Yes, syntactically, if your return type is a pointer type, nil is a valid value for that type. As to whether you should, that's purely opinion-based.

    – Adrian
    Mar 27 at 13:19







1




1





There is no "best practice" here. Only opinion. Do what makes sense for your application.

– Flimzy
Mar 27 at 11:21





There is no "best practice" here. Only opinion. Do what makes sense for your application.

– Flimzy
Mar 27 at 11:21













"can simply return nil as the value instead of returning an error"? Yes, syntactically, if your return type is a pointer type, nil is a valid value for that type. As to whether you should, that's purely opinion-based.

– Adrian
Mar 27 at 13:19





"can simply return nil as the value instead of returning an error"? Yes, syntactically, if your return type is a pointer type, nil is a valid value for that type. As to whether you should, that's purely opinion-based.

– Adrian
Mar 27 at 13:19












2 Answers
2






active

oldest

votes


















0














If you are using gorm, there is a function specifically for that; namely,



// IsRecordNotFoundError returns true if error contains a RecordNotFound error
func IsRecordNotFoundError(err error) bool


You can use it as following:



err = db.Find(object).Error
if err != nil
if gorm.IsRecordNotFoundError(err)
// handle object not found
else
return err




and for your question:




I'm wondering you can simply return nil as the value instead of returning an error




It really depends on your design; so if you want to separate your database layer, then you should still inform the user about this error using your own exported error type and let them handle it as they wish.






share|improve this answer


































    0














    you can use this code:



     user:=&User
    if db.First(&user, "username=?", mobile).RecordNotFound()
    return nil

    return user





    share|improve this answer



























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55372748%2fproper-error-handling-when-no-entity-is-found%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      If you are using gorm, there is a function specifically for that; namely,



      // IsRecordNotFoundError returns true if error contains a RecordNotFound error
      func IsRecordNotFoundError(err error) bool


      You can use it as following:



      err = db.Find(object).Error
      if err != nil
      if gorm.IsRecordNotFoundError(err)
      // handle object not found
      else
      return err




      and for your question:




      I'm wondering you can simply return nil as the value instead of returning an error




      It really depends on your design; so if you want to separate your database layer, then you should still inform the user about this error using your own exported error type and let them handle it as they wish.






      share|improve this answer































        0














        If you are using gorm, there is a function specifically for that; namely,



        // IsRecordNotFoundError returns true if error contains a RecordNotFound error
        func IsRecordNotFoundError(err error) bool


        You can use it as following:



        err = db.Find(object).Error
        if err != nil
        if gorm.IsRecordNotFoundError(err)
        // handle object not found
        else
        return err




        and for your question:




        I'm wondering you can simply return nil as the value instead of returning an error




        It really depends on your design; so if you want to separate your database layer, then you should still inform the user about this error using your own exported error type and let them handle it as they wish.






        share|improve this answer





























          0












          0








          0







          If you are using gorm, there is a function specifically for that; namely,



          // IsRecordNotFoundError returns true if error contains a RecordNotFound error
          func IsRecordNotFoundError(err error) bool


          You can use it as following:



          err = db.Find(object).Error
          if err != nil
          if gorm.IsRecordNotFoundError(err)
          // handle object not found
          else
          return err




          and for your question:




          I'm wondering you can simply return nil as the value instead of returning an error




          It really depends on your design; so if you want to separate your database layer, then you should still inform the user about this error using your own exported error type and let them handle it as they wish.






          share|improve this answer















          If you are using gorm, there is a function specifically for that; namely,



          // IsRecordNotFoundError returns true if error contains a RecordNotFound error
          func IsRecordNotFoundError(err error) bool


          You can use it as following:



          err = db.Find(object).Error
          if err != nil
          if gorm.IsRecordNotFoundError(err)
          // handle object not found
          else
          return err




          and for your question:




          I'm wondering you can simply return nil as the value instead of returning an error




          It really depends on your design; so if you want to separate your database layer, then you should still inform the user about this error using your own exported error type and let them handle it as they wish.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 27 at 8:48

























          answered Mar 27 at 8:42









          AbdullahAbdullah

          1,0711 gold badge7 silver badges18 bronze badges




          1,0711 gold badge7 silver badges18 bronze badges


























              0














              you can use this code:



               user:=&User
              if db.First(&user, "username=?", mobile).RecordNotFound()
              return nil

              return user





              share|improve this answer





























                0














                you can use this code:



                 user:=&User
                if db.First(&user, "username=?", mobile).RecordNotFound()
                return nil

                return user





                share|improve this answer



























                  0












                  0








                  0







                  you can use this code:



                   user:=&User
                  if db.First(&user, "username=?", mobile).RecordNotFound()
                  return nil

                  return user





                  share|improve this answer













                  you can use this code:



                   user:=&User
                  if db.First(&user, "username=?", mobile).RecordNotFound()
                  return nil

                  return user






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 27 at 14:15









                  morteza khademmorteza khadem

                  815 bronze badges




                  815 bronze badges






























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55372748%2fproper-error-handling-when-no-entity-is-found%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript