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
相关推荐
Ulyanov5 小时前
高保真单脉冲雷达导引头回波生成:Python建模与实践
开发语言·python·仿真·系统设计·单脉冲雷达
阿猿收手吧!6 小时前
【C++】jthread:优雅终止线程新方案
开发语言·c++
苍何6 小时前
即梦Seedance2.0海外火爆出圈,AI 视频的 DeepSeek 时刻来了!(附实测教程)
后端
lly2024066 小时前
《JavaScript 实例》
开发语言
苍何6 小时前
阿里卷麻了,千问 Qwen-Image-2.0 发布,超强文字渲染、信息图、PPT 轻松做(附实测提示词)
后端
苍何6 小时前
被马斯克疯狂点赞的国产 AI,很可能是 AI 时代的抖音!
后端
苍何7 小时前
国产Windows 版 Claude Cowork 来了,内置海量 Skills,绝了。
后端
十五年专注C++开发7 小时前
C++中各平台表示Debug的宏
开发语言·c++·debug
张小凡vip7 小时前
Python异步编程实战:基于async/await的高并发实现
开发语言·python
玩c#的小杜同学7 小时前
源代码保卫战:给C# 程序(混淆、加壳与反逆向实战)
开发语言·笔记·c#