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

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현