ZVVQ代理分享网

golang框架如何自定义错误返回?(golang 优雅错误

作者:zvvq博客网
导读在 golang 框架中,通过继承 errors.error 接口创建自定义错误类型,使用 errors.new() 函数创建错误,并在处理程序函数中使用 http.error() 函数将自定义错误返回给调用方,从而实现自定义错

golang 框架中,通过继承 errors.error 接口创建自定义错误类型,使用 errors.new() 函数创建错误,并在处理程序函数中使用 http.error() 函数将自定义错误返回给调用方,从而实现自定义错误返回。包括:1. 创建自定义错误类型;2. 创建错误;3. 返回自定义错误。

Golang 框架中自定义错误返回

在编写 Go 应用程序时,返回自定义错误非常重要,这有助于提供有意义和可操作的信息,从而便于调试和错误处理。本文将介绍如何使用标准库中的 errors 包在 Golang 框架中自定义错误返回。

创建自定义错误类型

”;

首先,创建一个自定义错误类型,它通常继承自 errors.error 接口:

1

2

3

4

5

6

7

8

9

package errors

type MyCustomError struct {

message string

}

func (e MyCustomError) Error() string {

return e.message

}

创建错误

使用 New() 函数来创建一个新的自定义错误:

1

err := errors.New("invalid input")

传递一个字符串参数来设置错误消息。

返回自定义错误

然后,可以使用自定义错误类型从处理程序函数返回自定义错误:

1

2

3

4

5

6

7

8

func handler(w http.ResponseWriter, r http.Request) {

// 处理请求...

if err != nil {

http.Error(w, err.Error(), http.StatusBadRequest)

return

}

}

http.Error() 函数接受一个 error 参数,并将其写入响应作为错误消息。

实战案例

以下是一个处理 RESTful API 中用户更新请求的真实案例 :

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

package handlers

import (

"errors"

"fmt"

"net/http"

"<a style=color:f60; text-decoration:underline; href="https://www.zvvq.cn/zt/15841.html" target="_blank">git</a>hub.com/gorilla/mux"

)

type UpdateUserRequest struct {

Name string `json:"name"`

Age  int    `json:"age"`

}

// UserService represents a service for handling user-related operations.

type UserService interface {

UpdateUser(ctx context.Context, req UpdateUserRequest) error

}

type UserHandler struct {

userService UserService

}

func NewUserHandler(userService UserService) UserHandler {

return &UserHandler{userService: userService}

}

// UpdateUser handles a request to update a user.

func (h UserHandler) UpdateUser(w http.ResponseWriter, r http.Request) {

// Parse and validate the request body.

req := &UpdateUserRequest{}

if err := json.NewDecoder(r.Body).Decode(req); err != nil {

http.Error(w, "invalid request body", http.StatusBadRequest)

return

}

if req.Name == "" {

http.Error(w, "name is required", http.StatusBadRequest)

return

}

if req.Age < 0 {

http.Error(w, "age must be a positive integer", http.StatusBadRequest)

return

}

// Call the service to update the user.

if err := h.userService.UpdateUser(r.Context(), req); err != nil {

switch err {

case errors.New("user not found"):

http.Error(w, "user not found", http.StatusNotFound)

case errors.New("insufficient permissions"):

http.Error(w, "insufficient permissions", http.StatusForbidden)

default:

http.Error(w, fmt.Sprintf("internal server error: %s", err), http.StatusInternalServerError)

}

return

}

w.WriteHeader(http.StatusNoContent)

}

在这个例子中,UpdateUser() 处理程序函数通过将自定义错误返回给调用方来处理错误条件。具体来说,它返回以下错误:

errors.New("user not found"):返回给 http.Error() 函数,并导致 404 状态代码。 errors.New("insufficient permissions"):返回给 http.Error() 函数,并导致 403 状态代码。 fmt.Sprintf("internal server error: %s", err):用于处理未预期的错误,并返回 500 状态代码。

以上就是golang框架如何自定义错误返回?的详细内容,更多请关注其它相关文章!