首页 > 其他分享 >Go - Creating Customized Errors

Go - Creating Customized Errors

时间:2023-09-29 10:22:20浏览次数:38  
标签:Errors Creating err error struct custom Error Go string

Problem: You want to create custom errors to communicate more information about the error encountered.


Solution: Create a new string - based error or implement the error interface by creating a struct with an Error method that returns a string.

 

There are different ways of creating errors (in a good way).
Using a string - based error

err := errors . New ( "Syntax error in the code" )

err := fmt . Errorf ( "Syntax error in the code at line %d" , line )

Implementing the error interface

type   error   interface   { 
      Error ()   string 
}

As you can see, any struct with a method named Error that returns a string is an error. So if you want to define a custom error to return a custom error message, implement a struct and add an Error method. For example, let’s say you are writing a program used for communications and want to create a custom error to represent an error during communications:

type   CommsError   struct {} 

func   ( m   CommsError )   Error ()   string   { 
      return   "An  error  happened  during  data  transfer." 
}

You want to provide information about where the error came from. To do this, you can create a custom error to provide the information. Of course, you usually wouldn’t override Error ; you can add fields and other methods to your custom error to carry more information:

type   SyntaxError   struct   { 
      Line   int 
      Col    int 
} 
 
func   ( err   * SyntaxError )   Error ()   string   {
     return   fmt . Sprintf ( "Error  at  line  %d,  column  %d" ,   err . Line ,   err . Col ) 
}

When you get such an error, you can typecast it using the “comma, ok” idiom (because if you typecast it and it’s not that type, it will panic), and extract the additional data for your processing:

if   err   !=   nil   { 
      err ,   ok   :=   err .( * SyntaxError ) 
      if   ok   { 
          //  do  something  with  the  error 
      }   else   { 
          //  do  something  else 
      } 
}

 

标签:Errors,Creating,err,error,struct,custom,Error,Go,string
From: https://www.cnblogs.com/zhangzhihui/p/17736825.html

相关文章

  • 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......
  • golang-select
    select的作用golang中的select就是用来监听和channel有关的IO操作,当IO操作发生时,触发相应的动作。select只能应用于channel的操作,既可以用于channel的数据接收,也可以用于channel的数据发送。如果select的多个分支都满足条件,则会随机的选取其中一个满足条件的分......