v0.11.0 schema errors
Feature: Define webrpc schema errors
You can now define your own custom schema errors in RIDL file, for example:
error 1 Unauthorized "unauthorized" HTTP 401
error 2 ExpiredToken "expired token" HTTP 401
error 3 InvalidToken "invalid token" HTTP 401
error 4 Deactivated "account deactivated" HTTP 403
error 5 ConfirmAccount "confirm your email" HTTP 403
error 6 AccessDenied "access denied" HTTP 403
error 7 MissingArgument "missing argument" HTTP 400
error 8 UnexpectedValue "unexpected value" HTTP 400
error 100 RateLimited "too many requests" HTTP 429
error 101 DatabaseDown "service outage" HTTP 503
error 102 ElasticDown "search is degraded" HTTP 503
error 103 NotImplemented "not implemented" HTTP 501
error 200 UserNotFound "user not found"
error 201 UserBusy "user busy"
error 202 InvalidUsername "invalid username"
error 300 FileTooBig "file is too big (max 1GB)"
error 301 FileInfected "file is infected"
error 302 FileType "unsupported file type"
Note: Unless specified, the default HTTP status for webrpc errors is HTTP 400
.
typescript@v0.11.0 breaking changes
- All errors thrown by webrpc client are now instance of
WebrpcError
, which extends JavaScriptError
. No need to re-throw errors anymore. error.msg
error.message
- by default, the error messages are "human-friendly", they don't contain any details about the backend error cause
- underlying backend error (for developers) is optionally available as
error.cause?
error.code
orerror.message
can be used as input for user-friendly error i18n translations
You can now check for explicit error class instance (as defined in RIDL schema) or against a generic WebrpcError
class.
try {
const resp = await testApiClient.getUser();
// setUser(resp.user)
} catch (error) {
if (error instanceof RateLimitedError) {
// retry with back-off time
}
if (error instanceof UnauthorizedError) {
// render sign-in page
}
if (error instanceof WebrpcError) {
console.log(error.status) // print response HTTP status code (ie. 4xx or 5xx)
console.log(error.code) // print unique schema error code; generic endpoint errors are 0
console.log(error.message) // print error message
console.log(error.cause) // print the underlying backend error -- ie. "DB error" - useful for debugging / reporting to Sentry
}
// setError(error.message)
}
golang@v0.11.0 breaking changes
Note: You can turn on -legacyErrors=true
flag on golang generator (ie. webrpc-gen -target=golang -legacyErrors=true -pkg=proto
) in order to preserve the deprecated functions and sentinel errors (see below). This will allow you to migrate your codebase to the new custom schema errors gradually.
The following werbrpc error functions and sentinel errors are now deprecated or removed:
proto.WrapError() // Deprecated.
proto.Errorf() // Deprecated.
proto.HTTPStatusFromErrorCode()
proto.IsErrorCode()
proto.ErrCanceled // Deprecated.
proto.ErrUnknown // Deprecated.
proto.ErrFail // Deprecated.
proto.ErrInvalidArgument // Deprecated.
proto.ErrDeadlineExceeded // Deprecated.
proto.ErrNotFound // Deprecated.
proto.ErrBadRoute // Deprecated.
proto.ErrAlreadyExists // Deprecated.
proto.ErrPermissionDenied // Deprecated.
proto.ErrUnauthenticated // Deprecated.
proto.ErrResourceExhausted // Deprecated.
proto.ErrFailedPrecondition // Deprecated.
proto.ErrAborted // Deprecated.
proto.ErrOutOfRange // Deprecated.
proto.ErrUnimplemented // Deprecated.
proto.ErrInternal // Deprecated.
proto.ErrUnavailable // Deprecated.
proto.ErrDataLoss // Deprecated.
proto.ErrNone // Deprecated.
The schema errors can now be returned from the RPC endpoints via:
func (s *RPC) RemoveUser(ctx context.Context, userID int64) (bool, error) {
r, _ := ctx.Value(proto.HTTPRequestCtxKey).(*http.Request)
if s.IsRateLimited(r) {
- return false, proto.Errorf(proto.ErrUnavailable, "rate limited")
+ return false, proto.ErrRateLimited // HTTP 429 per RIDL schema
}
_, err := s.DB.RemoveUser(ctx, userID)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
- return false, proto.Errorf(proto.ErrNotFound, "no such user(%v)", userID)
+ return false, proto.ErrUserNotFound
}
- return false, proto.WrapError(proto.ErrInternal, err, "")
+ return false, proto.ErrorWithCause(proto.ErrDatabaseDown, err)
}
return true, nil
}
You can also return any other Go error and webrpc will render generic proto.ErrWebrpcEndpoint
error automatically along with HTTP 400
status code.
return fmt.Errorf("some error")
The RPC client(s) can now assert the schema error type by their unique error code:
if err, ok := rpc.RemoveUser(ctx, userID); err != nil {
if errors.Is(proto.ErrRateLimited) {
// slow down; retry with back-off strategy
}
if errors.Is(proto.ErrUserNotFound) {
// handle
}
// etc.
}
Changelog
- e442000: Bump to v0.11.0 (@VojtechVitek)
- 71d6e69: Bump to v0.11.0 - regenerate examples (#199) (@VojtechVitek)
- 1e5d18b: Update links to migration guide (@VojtechVitek)
- bf6dd73: Update to latest Go and TS gens with schema support (#200) (@VojtechVitek)
- 503d4b5: Add Go 1.20 to CI matrix (#195) (@VojtechVitek)
- a6758ac: Add built-in webrpc errors (#196) (@VojtechVitek)
- ee01a05: Add interoperability test for error cause (#198) (@VojtechVitek)
- e8a5e62: Schema errors: HTTP status code must be between 400-599 (#197) (@VojtechVitek)
- a6758ac: Add built-in webrpc errors (#196) (@VojtechVitek)
Docker
docker pull ghcr.io/webrpc/webrpc-gen:v0.11.0
Example: docker run -v $PWD:$PWD ghcr.io/webrpc/webrpc-gen:v0.11.0 -schema=$PWD/api.ridl -target=golang
Homebrew
brew tap webrpc/tap
brew install webrpc-gen
Build from source
go install -ldflags="-s -w -X github.com/webrpc/webrpc.VERSION=v0.11.0" github.com/webrpc/webrpc/cmd/webrpc-gen@v0.11.0
Download binaries
macOS: amd64, arm64 (Apple Silicon)
Linux: amd64, arm64
Windows: amd64, arm64