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
相关推荐
科雷软件测试10 小时前
Python中itertools.product:快速生成笛卡尔积
开发语言·python
OOJO11 小时前
c++---list介绍
c语言·开发语言·数据结构·c++·算法·list
IT_陈寒12 小时前
React Hooks闭包陷阱:你以为的state可能早就过期了
前端·人工智能·后端
小码哥_常12 小时前
细说API:颠覆认知!重新认识RESTful的真正精髓
后端
用户990450177800912 小时前
基于flowable实现在线表单+工作流
后端
苏三说技术12 小时前
Artha已接入MCP,线上问题能用AI排查了!
后端
用户9623779544812 小时前
代码审计 | CC2 链 —— _tfactory 赋值问题 PriorityQueue 新入口
后端
笨笨饿13 小时前
29_Z变换在工程中的实际意义
c语言·开发语言·人工智能·单片机·mcu·算法·机器人
艾为电子13 小时前
【技术帖】让接口不再短命:艾为 C-Shielding™ Type-C智能水汽防护技术解析
c语言·开发语言
棉花骑士14 小时前
【AI Agent】面向 Java 工程师的Claude Code Harness 学习指南
java·开发语言