Skip to content

Conversation

@nwithan8
Copy link
Contributor

Description

We had previously incorrectly implemented "inheritance" (which really doesn't exist in Go) among our error types, which was causing "casting" issues if you wanted to check if a specific error (e.g. InvalidRequestError) was a subtype of a parent error type (e.g. ApiError).

This has been rectified by implementing the Unwrap method from the standard errors package, which specifically handles casting for sub-types of errors.

Users can now build casting if-else or switch-case blocks to analyze which specific type of error was returned by a given function. Ex:

        // Print different messages based on the error type
	if err != nil {
		// LibraryError is the base of all errors thrown in this library, should match
		var libraryError *easypost.LibraryError
		if errors.As(err, &libraryError) {
			fmt.Println("Library error")
			fmt.Println(libraryError.Message)
		}
	
		// APIError is the base of all errors thrown due to the API, and a subtype of LibraryError, should match
		var apiError *easypost.APIError
		if errors.As(err, &apiError) {
			fmt.Println("API error")
			fmt.Println(apiError.Message)
			fmt.Println(apiError.StatusCode)
			fmt.Println(apiError.Errors)
		}

		// ForbiddenError is an error due to a 403 status code, and a subtype of APIError, should match
		var forbiddenError *easypost.ForbiddenError
		if errors.As(err, &forbiddenError) {
			fmt.Println("Forbidden error")
			fmt.Println(forbiddenError.Message)
			fmt.Println(forbiddenError.StatusCode)
			fmt.Println(forbiddenError.Errors)
		}

		// Alternate way of checking type if you don't need the resultant casted variable
		if errors.As(err, new(*easypost.ForbiddenError)) {
			// Do something, no access to casted error type
		}
	}

Testing

  • Updated unit tests accordingly
  • Added new unit test to verify casting/inheritance tree for error types

Pull Request Type

Please select the option(s) that are relevant to this PR.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Improvement (fixing a typo, updating readme, renaming a variable name, etc.)

- Add unit test to confirm inheritance works as expected
@nwithan8 nwithan8 requested a review from a team August 12, 2024 19:25
@nwithan8 nwithan8 merged commit 7bd2358 into master Aug 13, 2024
@nwithan8 nwithan8 deleted the error_types branch August 13, 2024 21:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants