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
相关推荐
charlie1145141917 分钟前
IMX6ULL WM8960 的移植——前置介绍
开发语言·c++·开源项目·嵌入式linux
Codelinghu26 分钟前
AI 写代码越强,程序员越不能只懂代码
后端
迷迭香yy30 分钟前
Python实战:涨停板“假封板”识别系统的工程实现
开发语言·人工智能·python
卡卡敲码31 分钟前
Skills 撞车了,Agent 怎么选
后端
charlie11451419131 分钟前
Cinux是如何管理进程的 —— 上下文与调度
开发语言·c++·操作系统·开源项目
羑悻31 分钟前
周一早上三件事砸过来,我以为要延期,结果 AI 替我扛了一半!
后端
文艺理科生37 分钟前
3 年,8 种方案,1 次重构:LangChain 记忆方案如何从混乱走向清晰
前端·后端·架构
-银雾鸢尾-1 小时前
C#中的协变和逆变
开发语言·c#
阿米亚波1 小时前
【C++ 异常处理】try-catch
开发语言·c++·笔记·try-catch
Ai拆代码的曹操1 小时前
Agent 做错了怎么办?Self-Critique 机制拆解
后端·agent·ai编程