首页 > 其他分享 >Go - Inspecting Errors

Go - Inspecting Errors

时间:2023-09-29 14:33:05浏览次数:43  
标签:function Errors errors err ApiErr connect Inspecting error Go

Problem: You want to check for specific errors or specific types of errors.


Solution: Use the errors.Is and errors.As functions. The errors.Is function compares an error to a value and the errors.As function checks if an error is of a specific type.

 

Using errors.Is
The errors.Is function is essentially an equality check. Let’s say you define a set of customized errors in your codebase — for example, ApiErr — which happens when a connection to an API encounters an error:

var   ApiErr   error   =   errors . New ( "Error  trying  to  get  data  from  API" )

Elsewhere in your code, you have a function that returns this error:

func   connectAPI ()   error   { 
      //  some  other  stuff  happening  here 
      return   ApiErr 
}

You can use errors.Is to check if the error returned is ApiErr :

err   :=   connectAPI () 
if   err   !=   nil   { 
      if   errors . Is ( err ,   ApiErr )   { 
          //  handle  the  API  error 
      } 
}

You can also verify if ApiErr is somewhere along the chain of wrapped errors. Take the example of a connect function that returns a ConnectionError that wraps around ApiErr :

func   connect ()   error   { 
      return   & ConnectionError { 
          Host :   "localhost" , 
          Port :   8080 , 
          Err :    ApiErr , 
      } 
}

This code still works because ConnectionError wraps around ApiErr :

err   :=   connect () 
if   err   !=   nil   { 
      if   errors . Is ( err ,   ApiErr )   { 
          //  handle  the  API  error 
      } 
}

Using errors.As
The errors.As function allows you to check for a specific type of error. Continue with the same example, but this time around, you want to check if the error is of the type ConnectionError :

err   :=   connect () 
if   err   !=   nil   { 
      var   connErr   * ConnectionError 
      if   errors . As ( err ,   & connErr )   { 
          log . Errorf ( "Cannot  connect  to  host  %s  at  port  %d" ,   connErr . Host , 
          connErr . Port ) 
      } 
}

 

标签:function,Errors,errors,err,ApiErr,connect,Inspecting,error,Go
From: https://www.cnblogs.com/zhangzhihui/p/17736975.html

相关文章

  • MongoDB playground All In One
    MongoDBplaygroundAllInOneMongoDBREPLhttps://mongoplayground.net/db={"teacher":[{"_id":ObjectId("64fee9b54273ac2234441225"),"teacherid":ObjectId("64f1d72a4331bc8fc4c5930f"......
  • 关于一个django工程如何与达梦数据库连接的全程总结
    关于一个django工程如何与达梦数据库连接的全程总结目录1.达梦数据库的安装(win、图形化工具)2.DM管理工具的基本使用:表空间的建删用户的管理模式的建删表的创建、删除、查看3.Django项目接入dm数据库settings的database配置解释器中的相关包dmPython的编译※环境准备正式编......
  • Go - Wrapping an Error with Other Errors
    Problem: Youwanttoprovideadditionalinformationandcontexttoanerroryoureceivebeforereturningitasanothererror.Solution: Wraptheerroryoureceivewithanothererroryoucreatebeforereturningit. Thereareacoupleofwaystowraperr......
  • 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中编写单元测试的最佳实......