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
相关推荐
小声读源码8 分钟前
【技巧】使用UV创建python项目的开发环境
开发语言·python·uv·dify
yxc_inspire15 分钟前
基于Qt的app开发第七天
开发语言·c++·qt·app
zm-v-1593043398617 分钟前
解锁遥感数据密码:DeepSeek、Python 与 OpenCV 的协同之力
开发语言·python·opencv
周Echo周29 分钟前
20、map和set、unordered_map、un_ordered_set的复现
c语言·开发语言·数据结构·c++·算法·leetcode·list
明天更新34 分钟前
Java处理压缩文件的两种方式!!!!
java·开发语言·7-zip
老胖闲聊40 分钟前
C# 注册表操作类
开发语言·c#
勘察加熊人42 分钟前
Python+Streamlit实现登录页
开发语言·python
撸猫79143 分钟前
HttpSession 的运行原理
前端·后端·cookie·httpsession
理智的煎蛋1 小时前
keepalived+lvs
java·开发语言·集成测试·可用性测试
嘵奇1 小时前
Spring Boot中HTTP连接池的配置与优化实践
spring boot·后端·http