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
相关推荐
ZHE|张恒3 分钟前
设计模式(二)工厂方法模式 — 把创建权限下放给子类,像“可扩展的生产线”
java·开发语言·设计模式
报错小能手12 分钟前
C++笔记 bind函数模板
开发语言·c++·笔记
月弦笙音17 分钟前
【AI】👉提示词入门基础篇指南
前端·后端·aigc
2501_9411115237 分钟前
C++中的适配器模式
开发语言·c++·算法
2501_9411119437 分钟前
C++中的适配器模式变体
开发语言·c++·算法
zzz海羊39 分钟前
VSCode配置java中的lombok
java·开发语言·vscode
A-code43 分钟前
Git 多模块项目管理
java·开发语言
没头脑的男大1 小时前
Unet实现脑肿瘤分割检测
开发语言·javascript·ecmascript
hongweihao1 小时前
Kafka 消息积压了,同事跑路了
后端·spring cloud·kafka
2501_941111771 小时前
C++代码移植性设计
开发语言·c++·算法