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
相关推荐
犹豫的果冻布丁11 分钟前
从零给 DeepSeek Harness 写一个壁纸皮肤插件(已开源)
前端·后端
weixin_4316004412 分钟前
NestJS 入门(10):日志——为什么常用 Winston?
后端·学习·日志·nest.js·winston
步行cgn41 分钟前
MyBatis <where> 标签详解:让你的动态 SQL 更优雅、更安全
后端
灵析表格42 分钟前
灵析表格财务函数深度实用性分析与实操教程
开发语言·ai·json·excel·wps
RainCity1 小时前
Java Swing 自定义组件库分享(十六)
java·笔记·后端
沙盘客1 小时前
AFSIM 14篇 C++ 插件开发:扩展你的仿真能力
c++·后端
桦说编程1 小时前
如何对待中断异常:一个被吞掉的 InterruptedException 引发的思考
后端
LONGZETECH1 小时前
无人机组装调试实训高损耗痛点分析与虚拟仿真教学落地方案
c语言·开发语言·架构·无人机
菜冻鱼1 小时前
Python-sklearn-降维
开发语言·人工智能·python·机器学习·支持向量机·sklearn
luj_17682 小时前
大航海时代:沉浸式财商实战沙盒
c语言·开发语言·网络·经验分享·算法