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
相关推荐
2501_92495269几秒前
C++中的适配器模式
开发语言·c++·算法
Lear3 分钟前
【SpringBoot】 前后端参数命名踩坑记录:小驼峰变下划线导致接收不到参数
后端
良木生香5 分钟前
【C++初阶】:C++类和对象(中):类的默认成员函数---万字解说(最主要的四点)
c语言·开发语言·c++
☆5667 分钟前
C++安全编程指南
开发语言·c++·算法
无心水9 分钟前
【时间利器】4、JavaScript时间处理全解:Date/moment/dayjs/Temporal
开发语言·前端·javascript·状态模式·openclaw·date/moment·dayjs/temporal
星轨初途12 分钟前
类和对象(中):六大默认成员函数与运算符重载全解析
开发语言·c++·经验分享·笔记·ajax·servlet
骇客野人13 分钟前
用python实现一个查询当天天气的MCP服务器
服务器·开发语言·python
天空属于哈夫克317 分钟前
拒绝被动响应:企业微信主动调用接口高阶方案
开发语言·python
2501_9419820520 分钟前
Go 语言实现企业微信外部群消息主动推送方案
开发语言·golang·企业微信
南山love22 分钟前
spring-boot多线程并发执行任务
java·开发语言