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
相关推荐
越城16 分钟前
C 语言联合与枚举:自定义类型的核心解析
c语言·开发语言
weixin_3077791320 分钟前
实现Azure Function安全地请求企业内部API返回数据
开发语言·python·云计算·azure
无敌的牛22 分钟前
list容器介绍及模拟实现和与vector比较
开发语言·数据结构·list
小菜刀刀28 分钟前
XSS跨站脚本攻击漏洞
开发语言·前端·javascript
Leon-zy38 分钟前
【Python笔记 01】变量、标识符
开发语言·python
CodeSheep39 分钟前
JetBrains再出手,最新IntelliJ IDEA 2025.1正式登场!
前端·后端·github
想不明白的过度思考者44 分钟前
Java从入门到“放弃”(精通)之旅——类和对象全面解析⑦
java·开发语言
七月丶1 小时前
🚀 从 Git 操作痛点出发,我为什么开发了 gix?
前端·后端·github
知其然亦知其所以然1 小时前
大模型时代,Java开发者别落伍!LangChain4j让你轻松追上
java·人工智能·后端
绝了1 小时前
Go的手动内存管理方案
后端·算法·go