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
相关推荐
Evand J3 分钟前
【MATLAB例程,无人机避障7】基于RRT*与人工势场法(RRT*+APF)的多无人机二维动态路径规划与避障。附下载链接
开发语言·matlab·无人机·rtt·路径规划·人工势场
布莱克6053 分钟前
Objective-C 基本语法详解:从零开始掌握 iOS 开发语言
开发语言·ios·objective-c·基础·语法
oil欧哟21 分钟前
为什么我们不建议盲目构建多 Agent 系统
前端·后端
利威尔xu36 分钟前
2026-11-25-Go-panic-recover面试
面试·golang
码途行者41 分钟前
每天10分钟学Go:第24课 通道-协程之间的传送带
开发语言·后端·golang
SimonKing41 分钟前
别OCR了,都在用了OXR了,看那看那这款开源的OXR产品
java·后端·程序员
Rain的Java大神之路1 小时前
DTO、VO、PO 到底要不要拆?这场 Java 分层之争,今天一次讲透
java·后端·面试
Moment1 小时前
怎么给客户讲清本体、知识图谱和大模型的关系
前端·后端·面试
CoderYanger1 小时前
Java EE 进阶:14.案例综合练习-博客系统(第三弹) :用户登录+强制登录
java·服务器·开发语言·数据库·spring boot·java-ee·mybatis