How to handle HTTP errors in Golang?

WBOY
Release: 2024-06-03 10:15:57
Original
509 people have browsed it

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
)
Copy after login

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)
}
Copy after login

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
    }

    // ... 继续处理请求
}
Copy after login

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")
Copy after login

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)
    }
}
Copy after login

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
    }

    // ... 继续处理请求
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!