Home > Backend Development > Golang > How to Gracefully Handle and Return Errors in Go HTTP Request Handling?

How to Gracefully Handle and Return Errors in Go HTTP Request Handling?

Linda Hamilton
Release: 2024-11-27 06:50:12
Original
754 people have browsed it

How to Gracefully Handle and Return Errors in Go HTTP Request Handling?

Terminating an HTTP Request with Error Handling

When developing API services using HTTP in Go, it may be necessary to abort a request and return an error message if certain conditions are not met. To achieve this, the ServeHTTP() method can be used effectively.

Returning from ServeHTTP()

To terminate an HTTP request, return from the ServeHTTP() method. By doing so, the request will be halted, and a response can be sent through fmt.Fprint(w, str) or similar methods. For example:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    // Examine incoming params
    if !ok {
        str := `{"Result":"","Error":"No valide Var"}`
        fmt.Fprint(w, str)
        return
    }

    // Do normal API serving
})
Copy after login

HTTP Error Codes

In cases where the input parameters are invalid, sending an HTTP error code (e.g., 400 for Bad Request) instead of the default 200 OK is recommended. The http.Error() function can be used for this purpose:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    // Examine incoming params
    if !ok {
        http.Error(w, "Invalid input params!", http.StatusBadRequest) 
        return
    }

    // Do normal API serving
})
Copy after login

Returning JSON Data with an Error Code

To send back JSON data along with an error code, the Header().Set() method can be used to set the Content-Type header, and the WriteHeader() method can be used to set the HTTP status code:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    // Examine incoming params
    if !ok {
        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusBadRequest) 
        str := `{"Result":"","Error":"No valide Var"}`
        fmt.Fprint(w, str)
        return
    }

    // Do normal API serving
})
Copy after login

Propagating Returning

When the error is detected outside of ServeHTTP(), the error state must be propagated so that ServeHTTP() can return. A simple approach is to return the error from the inner function, which will cause the ServeHTTP() method to return as well. For example, with a custom params type:

type params struct {
    // fields for your params 
}

func decodeParams(r *http.Request) (*params, error) {
    p := new(params)
    // decode params; if they are invalid, return an error:

    if !ok {
        return nil, errors.New("Invalid params")
    }

    // If everything goes well:
    return p, nil
}

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    p, err := decodeParams(r)
    if err != nil {
        http.Error(w, `Invalid input params!`, http.StatusBadRequest)
        return
    }

    // Do normal API serving
})
Copy after login

By utilizing these approaches, you can effectively terminate HTTP requests and return meaningful error messages when necessary, ensuring that your API services handle invalid inputs gracefully and communicate error conditions as intended.

The above is the detailed content of How to Gracefully Handle and Return Errors in Go HTTP Request Handling?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template