anz-bank / sysl-go

Communication library used by SYSL-generated code written in Go.
Apache License 2.0
10 stars 14 forks source link

Proposal: Change HTTPError from struct to interface #209

Open JackLeeHal opened 4 years ago

JackLeeHal commented 4 years ago

Purpose

Currently error response struct is:

type HTTPError struct { HTTPCode int json:"-" Code string json:"code,omitempty" Description string json:"description,omitempty"

extraFields map[string]interface{} }

But in some situations we want a different specific error type. Especially when errors were handled by the generated code(like missing header error). We don't have control on the error struct in this situation.

Suggested approaches

change struct to interface, so we can implement our own error type.

type HTTPError interface {
    AddField(key string, val interface{})
    WriteError(ctx context.Context, w http.ResponseWriter)
}
type DefaultHTTPError struct {
    HTTPCode    int    `json:"-"`
    Code        string `json:"code,omitempty"`
    Description string `json:"description,omitempty"`

    extraFields map[string]interface{}
}
type CustomHTTPError struct {
...
}
anzdaddy commented 4 years ago

@JackLeeHal what's the use case for implementing your own error type? You may be able to just include the existing struct in your type:

type MyHTTPError struct {
    common.HTTPError
    …
}
JackLeeHal commented 4 years ago

@anzdaddy Our use case is:

When error was handled by generated code. i.e. missing header error. This kind of error will be return directly by framework. And currently we have an API which is a migration one, need different format for this kind of error response.

In this case, framework will just return: {"status": {"code":"1001", "description":"Missing one or more of the required parameters"}}

But we need: {"status": {"statusCode":"1001", "statusDesc":"Missing one or more of the required parameters"}}

This kind of error will always return as a struct common.HTTPError which will not fit our requirement.