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
相关推荐
hackchen2 分钟前
Go与JS无缝协作:Goja引擎实战之错误处理最佳实践
开发语言·javascript·golang
南雨北斗44 分钟前
TP6使用PHPMailer发送邮件
后端
你的人类朋友1 小时前
🤔什么时候用BFF架构?
前端·javascript·后端
铲子Zzz1 小时前
Java使用接口AES进行加密+微信小程序接收解密
java·开发语言·微信小程序
小小小新人121232 小时前
C语言 ATM (4)
c语言·开发语言·算法
Two_brushes.2 小时前
【linux网络】网络编程全流程详解:从套接字基础到 UDP/TCP 通信实战
linux·开发语言·网络·tcp/udp
小白学大数据2 小时前
R语言爬虫实战:如何爬取分页链接并批量保存
开发语言·爬虫·信息可视化·r语言
争不过朝夕,又念着往昔2 小时前
Go语言反射机制详解
开发语言·后端·golang
Jerry Lau2 小时前
go go go 出发咯 - go web开发入门系列(二) Gin 框架实战指南
前端·golang·gin
Azxcc02 小时前
C++异步编程入门
开发语言·c++