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
相关推荐
码云骑士5 分钟前
03-Python可变对象与不可变对象(下)-深浅拷贝的底层真相
开发语言·python
砍材农夫6 分钟前
python环境|pip|uv|venv|Conda区别
后端·python·conda·pip·uv
sycmancia7 分钟前
Qt——自定义模型类
开发语言·qt
MATLAB代码顾问13 分钟前
Python数据分析项目实战:销售数据仪表盘
开发语言·python·数据分析
Csvn13 分钟前
Linux 网络配置与排查命令实战
后端
码云骑士14 分钟前
07-Python装饰器从入门到源码(下)-带参数装饰器与wraps
开发语言·python
LAM LAB15 分钟前
【Web】网页如何模拟移动端获取定位\定位模拟测试
开发语言·前端·javascript
小糯米60117 分钟前
C语言文件操作
c语言·开发语言·数据结构
caimouse18 分钟前
Reactos 第 9 章 设备驱动 — 9.4 内核劳务线程
开发语言·windows
IT_陈寒18 分钟前
Redis主从切换把我坑惨了,这份血泪史你最好看看
前端·人工智能·后端