Go语言入门到入土——三、处理并返回异常

Go语言入门到入土------三、处理并返回异常


文章目录


1. 在greetings.go中添加异常处理代码

处理空输入的异常,代码如下:

go 复制代码
package greetings

import (
    "errors"
    "fmt"
)

// Hello returns a greeting for the named person.
func Hello(name string) (string, error) {
    // If no name was given, return an error with a message.
    if name == "" {
        return "", errors.New("empty name")
    }

    // If a name was received, return a value that embeds the name
    // in a greeting message.
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message, nil
}

2. 在hello.go中添加日志记录代码

记录空异常的日志代码如下:

go 复制代码
package main

import (
    "fmt"
    "log"

    "example.com/greetings"
)

func main() {
    // Set properties of the predefined Logger, including
    // the log entry prefix and a flag to disable printing
    // the time, source file, and line number.
    log.SetPrefix("greetings: ")
    log.SetFlags(0)

    // Request a greeting message.
    message, err := greetings.Hello("")
    // If an error was returned, print it to the console and
    // exit the program.
    if err != nil {
        log.Fatal(err)
    }

    // If no error was returned, print the returned message
    // to the console.
    fmt.Println(message)
}

3. 运行

bash 复制代码
go run main.go

结果如下:

bash 复制代码
greetings: empty name
exit status 1
相关推荐
ShaneD7715 分钟前
解决idea错误提示:无法解析'表名'
后端
while(1){yan}9 分钟前
多线程CAS八股文
java·开发语言·面试
飞Link14 分钟前
【轻量拓展区】网络 QoS 与带宽、延迟、抖动:AI 推理的性能瓶颈
开发语言·网络·人工智能
李拾叁的摸鱼日常15 分钟前
从 Java 8 升级视角看Java 17 新特性详解
java·后端
淡定__00915 分钟前
深入理解 .NET 中的依赖注入(DI):从原理到实战
后端
Haoea!23 分钟前
jkd8特性
开发语言
Ankkaya25 分钟前
小白服务器踩坑(2)- 自动化部署
后端
回家路上绕了弯25 分钟前
Vavr 工具实用指南:Java 函数式编程的高效落地方案
分布式·后端
开心就好202528 分钟前
没有 Mac 怎么上架 iOS 应用 跨平台团队的可行交付方案分析
后端
aiopencode35 分钟前
构建可靠的 iOS 日志导出体系,从真机日志到系统行为的多工具协同实践
后端