stripe / stripe-go

Go library for the Stripe API.
https://stripe.com
MIT License
2.17k stars 460 forks source link

Add MsgCode to Error #1909

Closed wozaki closed 3 months ago

wozaki commented 3 months ago

Background Summary

The current Error struct does not include a field to store the message_code. This requires writing additional code to extract the message_code from RawJSON when handling specific errors, such as checking if an invoice is already paid.

Detailed Description

When executing POST /v1/invoice/:id/pay on an already paid invoice, the following error is returned:

{
  "error": {
    "message": "foo",
    "message_code": "invoice_already_paid",
    "request_log_url": "https://dashboard.stripe.com/test/logs/foo",
    "type": "invalid_request_error"
  }
}

Currently, since the Error struct does not have a field that includes message_code, it is necessary to write code to extract message_code from RawJSON.

The example of Before and After of this modification is as follows:

// Before
var stripeErr *stripe.Error
if errors.As(err, &stripeErr) {
    switch stripeErr.Type {
    case stripe.ErrorTypeInvalidRequest:
        if stripeErr.LastResponse != nil {
            var responseBody map[string]interface{}
            jsonErr := json.Unmarshal(stripeErr.LastResponse.RawJSON, &responseBody)
            if jsonErr != nil {
                return jsonErr
            }
            if errorObj, ok := responseBody["error"].(map[string]interface{}); ok {
                messageCode, _ := errorObj["message_code"].(string)
                if messageCode == "invoice_already_paid" {
                    // Process for already paid invoice
                }
            }
        }
    }
}

// After
var stripeErr *stripe.Error
if errors.As(err, &stripeErr) {
    switch stripeErr.Type {
    case stripe.ErrorTypeInvalidRequest:
        if stripeErr.MsgCode == "invoice_already_paid" {
            // Process for already paid invoice
        }
    }
}
CLAassistant commented 3 months ago

CLA assistant check
All committers have signed the CLA.

remi-stripe commented 3 months ago

@wozaki The message_code property on the Error API resource is not a public feature. It does exist but it's purely internal to Stripe and shouldn't be exposed anywhere in the public API today (though you can sometimes see it in error messages on the Dashboard or via Workbench. This means we wouldn't add this feature to our public server-side SDKs.

Can you confirm that this maps to what you were seeing and that you do not see this property in our public API today?

wozaki commented 3 months ago

@remi-stripe Thank you for your review. Upon further review, I confirmed that the message_code property only appears in error responses via the Dashboard. I also understand that it should not be used in the public API at this time. I will go ahead and close this Pull Request.