Home  >  Article  >  Backend Development  >  Is it wrong to use type assertions for error handling?

Is it wrong to use type assertions for error handling?

WBOY
WBOYforward
2024-02-10 10:24:09891browse

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
    }
}

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
    }
}

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)

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete
Previous article:YAML custom tags in GoNext article:YAML custom tags in Go