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
相关推荐
RFG20126 小时前
20、详解Dubbo框架:消费方如何动态获取服务提供方地址?【微服务架构入门】
java·人工智能·后端·微服务·云原生·架构·dubbo
光泽雨6 小时前
C# 中 Assembly 类详解
开发语言·c#
少控科技6 小时前
C#基础训练营 - 02 - 运算器
开发语言·c#
Riemann~~7 小时前
C语言嵌入式风格
c语言·开发语言
TimberWill7 小时前
SpringBoot整合Srping Security实现权限控制
java·spring boot·后端
zmzb01039 小时前
C++课后习题训练记录Day104
开发语言·c++
桂花很香,旭很美9 小时前
[7天实战入门Go语言后端] Day 2:用 Go 写一个 HTTP 服务——net/http 入门
http·golang·xcode
zmzb01039 小时前
C++课后习题训练记录Day105
开发语言·c++·算法
wjs20249 小时前
Vue3 条件语句
开发语言
_codemonster9 小时前
JavaWeb开发系列(六)JSP基础
java·开发语言