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
相关推荐
卷无止境9 分钟前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
羑悻9 分钟前
别再只接个 API 了!我用 EdgeOne Makers 手搓了一个“懂业务”的官网售前 AI
后端
卷无止境1 小时前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
程序员威哥1 小时前
零基础玩转西门子PLC:C#手撕S7协议,打造工业数据采集神器
后端
用户742837256331 小时前
【Ambari Plus】Step9—AmbariServer 初始化
后端
wuxinzhe76cmd1 小时前
JVM 垃圾回收基础:从 STW 到分代收集(附 G1/ZGC 导读)
后端
MrSYJ1 小时前
TCP协议理解
后端·tcp/ip
boolean的主人1 小时前
超实用!5 个 MySQL 索引优化实战场景(附 10 万测试数据)
后端
BBmmo1 小时前
JDBC基础篇
后端
用户64278006937881 小时前
elpis-core 第一阶段学习心得与收获
后端