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
相关推荐
通往曙光的路上4 分钟前
SpringIOC-注解
java·开发语言
闲人编程5 分钟前
Python与大数据:使用PySpark处理海量数据
大数据·开发语言·分布式·python·spark·codecapsule·大规模
一 乐14 分钟前
校园墙|校园社区|基于Java+vue的校园墙小程序系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·后端·小程序
T.Ree.18 分钟前
汇编_读写内存
开发语言·汇编·c#
golang学习记32 分钟前
🍵 Go Queryx 入门指南:让数据库操作像喝奶茶一样丝滑!
后端
kaikaile199537 分钟前
基于MATLAB的直接序列扩频(DSSS)通信系统仿真实现
开发语言·matlab
stand_forever38 分钟前
PHP客户端调用由Go服务端GRPC接口
rpc·golang·php
czhc114007566342 分钟前
C#1114 枚举
开发语言·c#
z_鑫1 小时前
Java线程池原理深度解析
java·开发语言·后端
小呀小萝卜儿1 小时前
2025-11-14 学习记录--Python-特征归一化方法(Min-Max或StandardScaler)
开发语言·python·学习