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
相关推荐
花开彼岸天~3 分钟前
有日记日期标记:小圆点 + 加粗字重 + 点击跳转
后端
AskHarries8 分钟前
Google 登录配置
后端
全堆鸿蒙14 分钟前
时间轴组件:Circle 节点 + 竖线连接 + 内容列表
后端
wordpress资料库22 分钟前
Next.js更适合移动开发 不适合web开发
开发语言·前端·javascript·next.js
wujf9023 分钟前
Go 内存泄漏排查完整教程 (pprof)
开发语言·golang·xcode
言乐635 分钟前
Python实现基本搜索引擎
java·linux·开发语言·python·搜索引擎
爸爸61938 分钟前
WindowStage 窗口管理:透明状态栏与沉浸式布局
后端
进击的前栈41 分钟前
Grid 双栏网格与 List 单栏列表的视图切换实现
后端
xianjixiance_1 小时前
@Entry 与 @Component 装饰器:组件声明、导出与页面入口
后端
Wang's Blog1 小时前
Go-Zero项目开发5: 数据库与缓存一致性问题及 go-zero 缓存机制解析
数据库·缓存·golang