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
相关推荐
智塑未来几秒前
装备制造行业设计制造一体化痛点攻克与实战经验总结
java·开发语言·制造
Shadow(⊙o⊙)4 分钟前
硬核手搓解析!进程-内核分析:命令行参数及环境变量,重构main()
linux·运维·服务器·开发语言·c++·后端·学习
毋语天7 分钟前
Claude Code 完整安装与配置指南(含 CC-Switch 多供应商切换工具)
后端·python·ai编程
StackNoOverflow9 分钟前
RabbitMQ 入门详解(含安装 + 配置 + 管理后台)
开发语言·后端·ruby
2301_789015629 分钟前
Linux:基础指令(二)
linux·运维·服务器·c语言·开发语言·c++·算法
星晨羽13 分钟前
Java通过FTP协议实现文件上传下载
java·开发语言
阿拉金alakin18 分钟前
Java IO 核心类 File、InputStream/OutputStream 实战总结
java·开发语言
之歆18 分钟前
DAY_25 JavaScript 原型、原型链与值类型/引用类型 ── 深度全解(上)
开发语言·javascript·原型模式
csbysj202020 分钟前
C 标准库 - `<time.h>`
开发语言