Is it wrong to use type assertions for error handling?

WBOY
Release: 2024-02-10 10:24:09
forward
923 people have browsed it

Is it wrong to use type assertions for error handling?

Using type assertions for error handling is a common practice, but whether it is an error depends on the specific situation. Type assertions can be used to verify that the types of parameters passed in meet expectations, thereby catching errors in the code early. However, it can cause problems if error handling relies on type assertions and ignores other possible exceptions. Therefore, when using type assertions for error handling, you need to comprehensively consider the logic and reliability of the code, and ensure that various exceptions are properly handled to ensure the stability and maintainability of the code.

Question content

I wonder why switch type assertion style error handling is not used/recommended more in golang. What's wrong with it? Or does the community simply not care about it?

For example, the following code:

if err != nil {
    if errors.as(err, &queryerr{}) {
        log.println("query error : ", err)
        return http.statusinternalservererror
    } else if errors.as(err, &querydataextractionerr{}) {
        return http.statusnotfound
    } else {
        log.println(err.error())
        return http.statusinternalservererror
    }
}
Copy after login

can be written as:

if err != nil {
    switch err.(type) {
    case QueryErr:
        log.Println("query error : ", err)
        return http.StatusInternalServerError
    case QueryDataExtractionErr:
        return http.StatusNotFound
    default:
        log.Println(err.Error())
        return http.StatusInternalServerError
    }
}
Copy after login

Workaround

The type switch is technically correct. However, incorrect type switching can misinterpret wrapped errors. For example:

err:=io.EOF
err1 := fmt.Errorf("Unexpected error: %w",err)
Copy after login

Above, err1.(io.eof) will fail, but errors.is(err1,io.eof) will not.

Therefore, you should use errors.is and errors.as to test whether the error you have at hand contains the error you are looking for.

The above is the detailed content of Is it wrong to use type assertions for error handling?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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