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
相关推荐
脚本自动化开发7 小时前
玩影之刃零,两张四千元级显卡怎么挑
后端
starzy19909 小时前
深入理解Scala隐式类:扩展方法机制
开发语言·人工智能·scala
M--Y10 小时前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
用户479492835691511 小时前
从一句话或代码仓到可交互 HTML:开源 Agent 画图技能 Archify v3.2 实测与选型边界
前端·后端·面试
吴可可12311 小时前
WScript Shell操作注册表详解
开发语言
纪念 22912 小时前
C++ 算法基础 (差分)
开发语言·c++·算法
努力的小雨12 小时前
别再复制日志给AI了!我让Codex自己去观测云查报错
后端
afumu14 小时前
Go 写一个只监听 127.0.0.1 的控制服务:鉴权、白名单、危险命令拦截
后端·安全·go
johnjincaaaa15 小时前
猿人学第 18 题「jsvmp 洞察先机」逆向通关实录
javascript·后端
用户47027840040515 小时前
C语言编译与链接
后端·开源