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
相关推荐
RoyLin19 分钟前
TypeScript设计模式:适配器模式
前端·后端·node.js
该用户已不存在38 分钟前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
Moonbit42 分钟前
MoonBit 正式加入 WebAssembly Component Model 官方文档 !
前端·后端·编程语言
Goland猫1 小时前
电商架构图
后端
Java中文社群1 小时前
重要:Java25正式发布(长期支持版)!
java·后端·面试
我是天龙_绍1 小时前
Whisper 通过 mp3输出中文
后端
zjjuejin1 小时前
Maven环境搭建
后端·maven
我是天龙_绍1 小时前
项目根目录有requirements.txt 如何安装
后端
bobz9651 小时前
MPLS VPN | SRV6 TE 安全隔离路由技术
后端
bobz9652 小时前
AMD 正式停更 AMDVLK 驱动: 有格局的厂商和社区会是一致的
后端