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
相关推荐
江沉晚呤时1 分钟前
RabbitMQ 延迟队列实战指南:C# 版订单超时与定时任务解决方案
开发语言·后端·ruby
源码师傅2 分钟前
2026最新AI短剧创作系统源码 开发语言:PHP+MYSQL 无限SAAS 含图文搭建教程
开发语言·php·ai短剧创作系统源码·短剧创作系统·短剧创作源码
yujunl7 分钟前
AI工具帮助程序员做网页的经历
开发语言
6+h7 分钟前
【java IO】字符流详解
java·开发语言
ZHOUPUYU8 分钟前
PHP文件处理与安全实战——从上传下载到高级操作的完整指南
开发语言·php
小年糕是糕手8 分钟前
【35天从0开始备战蓝桥杯 -- 补充包】
开发语言·前端·数据结构·数据库·c++·算法·蓝桥杯
摸鱼的春哥14 分钟前
Agent教程20:更适合编程工具的记忆方案——情景摘要
前端·javascript·后端
Victor35616 分钟前
MongoDB(46)如何设计一个电商平台的数据库模型?
后端
Zzj_tju1 小时前
Java 从入门到精通(六):抽象类与接口到底怎么选?
java·开发语言