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
相关推荐
百***86463 分钟前
Spring Boot应用关闭分析
java·spring boot·后端
tanxiaomi4 分钟前
Spring、Spring MVC 和 Spring Boot ,mybatis 相关面试题
java·开发语言·mybatis
00后程序员4 分钟前
WebApp 上架 iOS 的可行性分析,审查机制、技术载体与工程落地方案的全流程说明
后端
Java水解6 分钟前
从零开始打造高性能数据结构——手把手教你实现环形缓冲
后端
浮尘笔记7 分钟前
Go并发编程核心:Mutex和RWMutex的用法
开发语言·后端·golang
散峰而望12 分钟前
C++数组(一)(算法竞赛)
c语言·开发语言·c++·算法·github
疯狂的程序猴13 分钟前
混淆 iOS 类名变量名,从符号隐藏到成品 IPA 混淆的工程化方案
后端
爱吃的小肥羊18 分钟前
GPT-5.1-Codex-Max正式发布,超越Gemini 3,编程能力第一!(附使用方法)
后端·aigc·openai
郡杰22 分钟前
Spring(2-IOC/DI管理第三方)
后端
洗澡水加冰32 分钟前
MCP与Skills的辨析
后端·aigc·mcp