Home  >  Article  >  Backend Development  >  How to handle HTTP errors in Golang?

How to handle HTTP errors in Golang?

WBOY
WBOYOriginal
2024-06-03 10:15:57509browse

Handling HTTP errors in Golang is crucial in order to respond gracefully to various error conditions in client requests. There are several ways to handle errors: Use built-in error types (for example: ErrBadRequest) to represent common HTTP errors. Create custom error types to handle custom error conditions. Use the httputil.NewError function to create a new error based on the status code and message.

如何在 Golang 中处理 HTTP 错误?

How to handle HTTP errors in Golang?

Handling HTTP errors in Golang is very important because it allows you to respond gracefully to various error conditions in client requests. Golang provides multiple ways to handle errors, including the built-in errors package.

Use built-in error types

Golang provides several built-in error types to represent common HTTP errors, such as:

import "net/http"

var (
    ErrBadRequest       = http.StatusBadRequest
    ErrUnauthorized     = http.StatusUnauthorized
    ErrForbidden        = http.StatusForbidden
    ErrNotFound         = http.StatusNotFound
    ErrMethodNotAllowed = http.StatusMethodNotAllowed
)

These error types can be used to return to clients terminal, indicating a specific error condition.

Use custom error types

If you need to handle custom error conditions, you can create your own error type:

type MyError struct {
    code    int
    message string
}

func (e *MyError) Error() string {
    return fmt.Sprintf("code: %d, message: %s", e.code, e.message)
}

Then you can return in the handler function This custom error:

func HandleRequest(w http.ResponseWriter, r *http.Request) {
    if err := validateRequest(r); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    // ... 继续处理请求
}

Use httputil.NewError

net/http/httputil package provides the NewError function , which can create a new error based on the given status code and error message:

err := httputil.NewError(http.StatusBadRequest, "Bad Request")

Practical case

Example 1: Using built-in error types

func HandleRequest(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case "GET":
        // ... 处理 GET 请求
    case "POST":
        // ... 处理 POST 请求
    default:
        http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
    }
}

Example 2: Using a custom error type

type InvalidRequestError struct {
    message string
}

func (e InvalidRequestError) Error() string {
    return fmt.Sprintf("invalid request: %s", e.message)
}

func HandleRequest(w http.ResponseWriter, r *http.Request) {
    if err := validateRequest(r); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    // ... 继续处理请求
}

The above is the detailed content of How to handle HTTP errors in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn