Home > other >  Go - errors.As() not recognising type
Go - errors.As() not recognising type

Time:03-26

I am using a helper function to decode JSON. It returns a custom error type that is populated with the reason why it could not parse the JSON and the HTTP code I should return.

package dto

type MalformedRequestError struct {
    Status  int
    Message string
}

func (mr *MalformedRequestError) Error() string {
    return mr.Message
}

One of the first things I do when decoding the body is to check that the client has correctly set the Content-Type header.

package webhandlers

func decodeJSONBody(w http.ResponseWriter, r *http.Request, dst interface{}) error {
    if r.Header.Get("Content-Type") != "" {
        value, _ := header.ParseValueAndParams(r.Header, "Content-Type")
        if value != "application/json" {
            Message := "Content-Type header is not application/json"
            return &dto.MalformedRequestError{Status: http.StatusUnsupportedMediaType, Message: Message}
        }
    }
    ... etc ...

I try to use errors.As() to check that the function is returning my custom error, but it is not working.

package webhandlers

func (i *InternalTokenHandler) Post(w http.ResponseWriter, r *http.Request) {
    type postRequest struct {
        Google_id_token string
    }
    // parse request data
    var parsedRequest postRequest
    err := decodeJSONBody(w, r, &parsedRequest)
    if err != nil {
        // outputs *dto.MalformedRequestError
        fmt.Println(fmt.Sprintf("%T", err))
        var mr *dto.MalformedRequestError
        if errors.As(err, &mr) {
            http.Error(w, mr.Message, mr.Status)
        } else {
            log.Println(err)
            http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
        }
        return
    }
    .... more code ...

I have checked that the type of the error is *dto.MalformedRequestError, but my code is always reaching the else block and returning the generic server 500 error.

What am I missing - why is errors.As() not recognizing the error type?

CodePudding user response:

This works: https://go.dev/play/p/CWe9mVp7QOz.

The only reason I can think of that would cause your code to fail, if it really does fail, is that the dto package used by decodeJSONBody is not the same as the dto package used by InternalTokenHandler.Post, hence the two error types would be different.

Note that even different versions of the same package count as different packages and types declared in those are not identical.

  •  Tags:  
  • go
  • Related