首页 > 其他分享 >Go - Wrapping an Error with Other Errors

Go - Wrapping an Error with Other Errors

时间:2023-09-29 10:33:06浏览次数:37  
标签:Errors struct err error Other Error Go errors err1

Problem: You want to provide additional information and context to an error you receive before returning it as another error.


Solution: Wrap the error you receive with another error you create before returning it.

 

There are a couple of ways to wrap errors. The easiest is to use fmt.Errorf again and provide an error as part of the parameter:

err1   :=   errors . New ( "Oops  something  happened." ) 
err2   :=   fmt . Errorf ( "An  error  was  encountered  -  %w" ,   err1 )

The %w verb allows you to place an error within the format string. In the example, err2 wraps err1 . But how do you extract err1 out of err2 ?
The errors package has an Unwrap function that does precisely this:

err   :=   errors . Unwrap ( err2 )

This will give you back err1 .

 

Another way of wrapping an error with an error is to create a customized error struct like this:

type   ConnectionError   struct   { 
      Host   string 
      Port   int 
      Err    error 
}

func   ( err   * ConnectionError )   Error ()   string   { 
      return   fmt . Sprintf ( "Error  connecting  to  %s  at  port  %d" ,   err . Host , 
      err . Port ) 
}

Remember, to make it an error, the struct should have an Error method. To allow the struct to be unwrapped, you need to implement an Unwrap function:

func   ( err   * ConnectionError )   Unwrap ()   error   { 
      return   err . Err 
}

 

标签:Errors,struct,err,error,Other,Error,Go,errors,err1
From: https://www.cnblogs.com/zhangzhihui/p/17736832.html

相关文章

  • Go - Creating Customized Errors
    Problem: Youwanttocreatecustomerrorstocommunicatemoreinformationabouttheerrorencountered.Solution: Createanewstring-basederrororimplementtheerrorinterfacebycreatingastructwithanErrormethodthatreturnsastring. Therea......
  • Go 语言概述
    本文主要包含以下内容:为什么需要一门新的语言Go 语言基本介绍Go 的发展历程Go 应用领域o 语言基本介绍在上述背景下,谷歌公司于 2009 年推出了新一代的编程语言 Go。提起 Go 语言的出身,我们就必须将我们饱含敬意的眼光投向持续推出惊世骇俗成果的贝尔实验室。贝尔实验室已......
  • 【代码分享】如何用go语言做一个简单的爬虫工具
    之前跟大家分享过一个简单的php做的爬虫,今天给大家带来一个使用golang来制作的一个简单的爬虫工具!大家看在中秋节我还更文的份上大家多评论转发收藏一下哟~也祝大家中秋节快乐安康~*使用colly来做一个简单的爬虫#安装collygogetgithub.com/gocolly/colly编写代码package......
  • Go - Simplifying Repetitive Error Handling
    Problem: Youwanttoreducethenumberoflinesofrepetitiveerror-handlingcode.Solution: Usehelperfunctionstoreducethenumberoflinesofrepetitiveerror-handlingcode. OneofthemostfrequentcomplaintsaboutGo’serrorhandling,especi......
  • 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......