首页 > 其他分享 >Go - Simplifying Repetitive Error Handling

Go - Simplifying Repetitive Error Handling

时间:2023-09-29 09:55:05浏览次数:29  
标签:function handling err Repetitive person Simplifying error Go check

Problem: You want to reduce the number of lines of repetitive error - handling code.


Solution: Use helper functions to reduce the number of lines of repetitive error - handling code.

 

One of the most frequent complaints about Go’s error handling, especially from newcomers, is that it’s tedious to do repetitive checks. Let’s take, for example, this piece of code that opens a JSON file to read and unmarshal to a struct:

func   unmarshal ()   ( person   Person )   { 
      r ,   err   :=   http . Get ( "https://swapi.dev/api/people/1" ) 
      if   err   !=   nil   { 
          //  handle  error 
      } 
      defer   r . Body . Close () 

      data ,   err   :=   io . ReadAll ( r . Body ) 
      if   err   !=   nil   { 
          //  handle  error 
      } 

      err   =   json . Unmarshal ( data ,   & person ) 
      if   err   !=   nil   { 
          //  handle  error 
      } 
      return   person 
}

You can see three sets of error handling: one when you call http.Get to get the API response into an http.Response , then when you call io.ReadAll to get the JSON text from the http.Response , and finally to unmarshal the JSON text into the Person struct. Each of these calls is a potential point of failure, so you need to handle errors that result from those failures.
However, these error - handling routines are similar to each other and, in fact, repetitive. How can you resolve this? There are several ways, but the most straightforward is using helper functions:

func   helperUnmarshal ()   ( person   Person )   { 
      r ,   err   :=   http . Get ( "https://swapi.dev/api/people/1" ) 
      check ( err ,   "Calling  SW  people  API" ) 
      defer   r . Body . Close () 

      data ,   err   :=   io . ReadAll ( r . Body ) 
      check ( err ,   "Read  JSON  from  response" ) 

      err   =   json . Unmarshal ( data ,   & person ) 
      check ( err ,   "Unmarshalling" ) 

      return   person 
} 

func   check ( err   error ,   msg   string )   { 
      if   err   !=   nil   { 
          log . Println ( "Error  encountered:" ,   msg ) 
          //  do  common  error - handling  stuff 
      } 
}

The helper function here is the check function that takes in an error and a string. Besides logging the string, you can also put all the common error - handling stuff that you want to do into the function. Instead of a string, you can also take in a function as a parameter and execute the function if an error is encountered.

标签:function,handling,err,Repetitive,person,Simplifying,error,Go,check
From: https://www.cnblogs.com/zhangzhihui/p/17736804.html

相关文章

  • Go - Using Multiple Versions of the Same Dependent Packages
    Problem: Youwanttousemultipleversionsofthesamedependentpackagesinyourcode.Solution: Usethereplacedirectiveinthego.modfiletorenameyourpackage.Thoughitmightseemlikeaverynicherequirement,thereissometimesaneedtobeabl......
  • Go - Requiring Local Versions of Dependent Packages
    Problem: Youwanttouselocalversionsofthedependentpackages.Solution: SetupGotouseavendordirectorybyrunninggomodvendor.Localversionsarethespecificversionofthedependentpackagesthatyoucanuseandareasafeguardincasethe......
  • Golang的测试、基准测试和持续集成
    在Golang中,内置的垃圾回收器处理内存管理,自动执行内存分配和释放。单元测试是软件开发中至关重要的一个方面,它确保了代码的正确性并在开发过程中尽早发现错误。在Go中,编写有效的单元测试非常简单,并为开发人员提供了对其代码的信心。在本文中,我们将探讨在Go中编写单元测试的最佳实......
  • golang编码规范
     目录[-]golang编码规范gofmt注释命名控制结构函数(必须)错误处理panicimport缩写参数传递接受者 golang编码规范注:此文档参考官方指南EffectiveGolang和GolangCodeReviewComments进行整理,力图与官方及社区编码风格保持一致。gofmt大部分的格式问题可以通过gofmt解决,gofmt自动......
  • 2023-09-13:用go语言,给定一个整数数组 nums 和一个正整数 k, 找出是否有可能把这个数组
    2023-09-13:用go语言,给定一个整数数组nums和一个正整数k,找出是否有可能把这个数组分成k个非空子集,其总和都相等。输入:nums=[4,3,2,3,5,2,1],k=4。输出:True。答案2023-09-13:第一种算法(canPartitionKSubsets1)使用动态规划的思想,具体过程如下:1.计算数组nums的总和sum......
  • 2023-09-10:用go语言编写。作为项目经理,你规划了一份需求的技能清单 req_skills, 并打算
    2023-09-10:用go语言编写。作为项目经理,你规划了一份需求的技能清单req_skills,并打算从备选人员名单people中选出些人组成一个「必要团队」(编号为i的备选人员people[i]含有一份该备选人员掌握的技能列表)。所谓「必要团队」,就是在这个团队中,对于所需求的技能列表req_skills......
  • golang-select
    select的作用golang中的select就是用来监听和channel有关的IO操作,当IO操作发生时,触发相应的动作。select只能应用于channel的操作,既可以用于channel的数据接收,也可以用于channel的数据发送。如果select的多个分支都满足条件,则会随机的选取其中一个满足条件的分......
  • python代码转成php代码的工具 或者go转成php的代码,想把odoo改成成php swoole当成web服
    目前市场上有一些可以将Python代码转换为PHP代码的工具,例如:Transcrypt:Transcrypt是一个将Python代码转换为JavaScript和PHP的工具。它可以将Python代码转换为相应的PHP代码,并保持语法和结构的一致性。Pythran:Pythran是一个专门用于加速Python代码执行的工具,但它也提供了将Python代......
  • Django实战项目-学习任务系统-需求说明
    一,需求说明在我最近的阅读中,我深深被一些关于智能或系统的小说吸引。这些小说的主角意外获得某种神秘的智能或系统,然后通过完成系统发布的各种任务,逐渐提升自己的知识和能力。即使是普通的屌丝,也能在系统的管理和奖励下,一步步实现自己的梦想。这种情景让我深感兴趣,于是我......
  • 100天精通Golang(基础入门篇)——第2天:学习Go语言的前世今生:一门强大的编程语言的崛起
    ......