search
HomeBackend DevelopmentPHP Tutorialgolang错误处理之error_PHP教程

golang错误处理之error

golang中没有try/catch这样的异常处理机制,只能依靠返回值来做状态是否出错判断(当然它有个panic/recover机制,但一般只处理意想不到的错误)。

对于函数的返回值,惯例是最后一个参数返回error对象,来表示函数运行的状态。
如:
  1. n, err := func()
  2. if err != nil {
  3. ...//process error
  4. }
或者写在一起
  1. if n, err := func(); err != nil {
  2. ...//process error
  3. }

error对象可以由errors.New()或fmt.Errorf()构造。
如:
  1. var dividedErr = errors.New("Cant divided by 0")

  1. err := fmt.Errorf("%d cant divided by 0", arg)

我们先来看看error到底是什么类型。
error在标准库中被定义为一个接口类型,该接口只有一个Error()方法:
  1. type error interface {
  2. Error() string
  3. }
也就是说,自定义的结构只需要拥有Error()方法,就相当于实现了error接口。


我们可以创建一个结构体,并实现Error()方法,就能根据自己的意愿构造error对象了。
如:
<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>type division struct {</li><li> arg int</li><li>        str string</li><li>}</li><li></li><li>func (e *division) Error() string {</li><li>        return fmt.Sprintf("%d %s", e.arg, e.str)</li><li>}</li><li></li><li>func divideCheck(arg1, arg2 int) (error) {</li><li>        if arg2 == 0 {</li><li>                return &division{arg1, "can't divided by 0"}</li><li>        }</li><li>        return nil</li><li>}</li></ol>

再来看一个例子,检查一组数据中是否有不能除(即除数为0)的情况,如果有则返回出错。
代码如下:
<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>package main</li><li></li><li>import "fmt"</li><li></li><li>func divideCheck(arg1, arg2 int) (error) {</li><li>        if arg2 == 0 {</li><li>                return fmt.Errorf("%d can't divided by 0", arg1)</li><li>        }</li><li>        return nil</li><li>}</li><li></li><li>func main() {</li><li>        var err error</li><li></li><li>        err = divideCheck(4, 2)</li><li>        if err != nil {</li><li>                fmt.Println(err)</li><li>                 return</li><li> }</li><li></li><li>        err = divideCheck(8, 0)</li><li>        if err != nil {</li><li>                fmt.Println(err)</li><li>                return</li><li>        }</li><li>}</li></ol>

我们实现了这个功能,但是这样的代码非常不优雅,每执行一次函数调用都至少要用3行来做错误处理。

下面来优化一下。我们需要实现的功能是,只要有一个数不能除,就返回出错。那么只需要把每次检查后的状态存储到内部状态变量里,在全部处理完成后再检查这个变量就行了。
代码如下:
<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>package main</li><li></li><li>import "fmt"</li><li></li><li>type division struct {</li><li> err error</li><li>}</li><li></li><li>func (this *division)DivideCheck(arg1, arg2 int) {</li><li> if this.err != nil {</li><li> return</li><li> }</li><li> if arg2 == 0 {</li><li> this.err = fmt.Errorf("%d can't divided by 0", arg1)</li><li> return</li><li> }</li><li>}</li><li></li><li>func (this *division)Err() error {</li><li>        return this.err</li><li>}</li><li></li><li>func main() {</li><li>        d := new(division)</li><li>        d.DivideCheck(4, 2)</li><li>        d.DivideCheck(8, 0)</li><li>        if d.Err() != nil {</li><li>                fmt.Println(d.Err())</li><li>        }</li><li>}</li></ol>
这么做代码就优雅多了,并且在每次检查前都判断内部状态是否已经出错,出错就马上返回,几乎没有性能损失。


golang的错误处理是经常被诟病的地方,但如果懂得以go的方式编程,还是可以做的挺优雅的~

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1114325.htmlTechArticlegolang错误处理之error golang中没有try/catch这样的异常处理机制,只能依靠返回值来做状态是否出错判断(当然它有个panic/recover机制,但一般只...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor