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
相关推荐
zhangjw342 小时前
Java基础语法:变量、数据类型与运算符,从原理到实战
java·开发语言
Wenweno0o5 小时前
Eino-Document 组件使用指南
golang·大模型·智能体·eino
yaoxin5211235 小时前
384. Java IO API - Java 文件复制工具:Copy 示例完整解析
java·开发语言·python
我叫黑大帅5 小时前
通过eino-ext如何正常indexer RAG?
后端·面试·go
NotFound4865 小时前
实战指南如何实现Java Web 拦截机制:Filter 与 Interceptor 深度分享
java·开发语言·前端
Ava的硅谷新视界6 小时前
用了一天 Claude Opus 4.7,聊几点真实感受
开发语言·后端·编程
rabbit_pro6 小时前
Python调用onnx模型
开发语言·python
浪客川7 小时前
【百例RUST - 010】字符串
开发语言·后端·rust
赵侃侃爱分享8 小时前
学完Python第一次写程序写了这个简单的计算器
开发语言·python
断眉的派大星8 小时前
# Python 魔术方法(魔法方法)超详细讲解
开发语言·python