package apperr import ( "errors" "net/http" "github.com/jackc/pgerrcode" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" grpcCodes "google.golang.org/grpc/codes" ) //go:generate stringer -type=Code -linecomment type Code uint16 const ( // CodeBadRequest = {AppError: BAD_REQUEST, HTTP:400} CodeBadRequest Code = iota // CodePayloadTooLarge = {AppError: REQUEST_ENTITY_TOO_LARGE, HTTP:413} CodePayloadTooLarge // CodeValidation = {AppError: VALIDATION, HTTP:400} CodeValidation // CodeUnauthorized = {AppError: UNAUTHORIZED, HTTP:401} CodeUnauthorized // CodeForbidden = {AppError: FORBIDDEN, HTTP:403} CodeForbidden // CodeNotFound = {AppError: NOT_FOUND, HTTP:404} CodeNotFound // CodeAlreadyExists = {AppError: ALREADY_EXISTS, HTTP:409} CodeAlreadyExists // CodeConflict = {AppError: CONFLICT, HTTP:409} CodeConflict // CodeTooManyRequests = {AppError: TOO_MANY_REQUESTS, HTTP:429} CodeTooManyRequests // CodeTimeout = {AppError: TIMEOUT, HTTP:504} CodeTimeout // CodeInternal = {AppError: INTERNAL, HTTP:500} CodeInternal // CodeServiceUnavailable = {AppError: SERVICE_UNAVAILABLE, HTTP:503} CodeServiceUnavailable // CodeOK = {AppError: OK, HTTP:200} CodeOK // CodeLocked = {AppError: LOCKED, HTTP:423} CodeLocked // CodeUnsupportedMediaType = {AppError: UNSUPPORTED_MEDIA_TYPE, HTTP:415} CodeUnsupportedMediaType // CodeUnavailable = {AppError: SERVICE_UNAVAILABLE, HTTP: 503} CodeUnavailable ) func (c Code) HTTPStatus() int { if status, ok := httpStatusByCode[c]; ok { return status } return http.StatusInternalServerError } func (c Code) GRPCCode() grpcCodes.Code { if code, ok := grpcCodeByCode[c]; ok { return code } return grpcCodes.Internal } func (c Code) PostgresCodes() []string { codes := postgresCodesByCode[c] if len(codes) == 0 { return nil } cp := make([]string, len(codes)) copy(cp, codes) return cp } func (c Code) PostgresCode() string { codes := c.PostgresCodes() if len(codes) == 0 { return "" } return codes[0] } func CodeFromError(err error) Code { if err == nil { return CodeInternal } var coded interface { Code() Code } if errors.As(err, &coded) { return coded.Code() } if code, ok := codeFromRedisError(err, false, false); ok { return code } return CodeFromPostgresError(err) } func HTTPStatusFromError(err error) int { return CodeFromError(err).HTTPStatus() } func GRPCCodeFromError(err error) grpcCodes.Code { return CodeFromError(err).GRPCCode() } func CodeFromHTTPStatus(status int) Code { if code, ok := codeByHTTPStatus[status]; ok { return code } return CodeInternal } func CodeFromGRPC(code grpcCodes.Code) Code { if appCode, ok := codeByGRPCCode[code]; ok { return appCode } return CodeInternal } func CodeFromPostgres(pgCode string) Code { if code, ok := codeByPostgresCode[pgCode]; ok { return code } return CodeInternal } func CodeFromPostgresError(err error) Code { if err == nil { return CodeInternal } if code, ok := codeByPgxError[err]; ok { return code } if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok { return CodeFromPostgres(pgErr.Code) } return CodeInternal } var ( httpStatusByCode = map[Code]int{ CodeBadRequest: http.StatusBadRequest, CodeUnauthorized: http.StatusUnauthorized, CodeForbidden: http.StatusForbidden, CodeNotFound: http.StatusNotFound, CodeAlreadyExists: http.StatusConflict, CodeConflict: http.StatusConflict, CodePayloadTooLarge: http.StatusRequestEntityTooLarge, CodeTooManyRequests: http.StatusTooManyRequests, CodeValidation: http.StatusBadRequest, CodeTimeout: http.StatusGatewayTimeout, CodeInternal: http.StatusInternalServerError, CodeServiceUnavailable: http.StatusServiceUnavailable, CodeUnsupportedMediaType: http.StatusUnsupportedMediaType, CodeUnavailable: http.StatusServiceUnavailable, CodeOK: http.StatusOK, CodeLocked: http.StatusLocked, } codeByHTTPStatus = map[int]Code{ http.StatusBadRequest: CodeBadRequest, http.StatusUnauthorized: CodeUnauthorized, http.StatusForbidden: CodeForbidden, http.StatusNotFound: CodeNotFound, http.StatusConflict: CodeConflict, http.StatusRequestEntityTooLarge: CodePayloadTooLarge, http.StatusTooManyRequests: CodeTooManyRequests, http.StatusUnprocessableEntity: CodeValidation, http.StatusGatewayTimeout: CodeTimeout, http.StatusInternalServerError: CodeInternal, http.StatusServiceUnavailable: CodeServiceUnavailable, http.StatusOK: CodeOK, http.StatusLocked: CodeLocked, http.StatusUnsupportedMediaType: CodeUnavailable, } grpcCodeByCode = map[Code]grpcCodes.Code{ CodeBadRequest: grpcCodes.InvalidArgument, CodePayloadTooLarge: grpcCodes.ResourceExhausted, CodeValidation: grpcCodes.InvalidArgument, CodeUnauthorized: grpcCodes.Unauthenticated, CodeForbidden: grpcCodes.PermissionDenied, CodeNotFound: grpcCodes.NotFound, CodeAlreadyExists: grpcCodes.AlreadyExists, CodeConflict: grpcCodes.Aborted, CodeTooManyRequests: grpcCodes.ResourceExhausted, CodeTimeout: grpcCodes.DeadlineExceeded, CodeInternal: grpcCodes.Internal, CodeServiceUnavailable: grpcCodes.Unavailable, CodeOK: grpcCodes.OK, CodeLocked: grpcCodes.FailedPrecondition, } codeByGRPCCode = map[grpcCodes.Code]Code{ grpcCodes.InvalidArgument: CodeBadRequest, grpcCodes.ResourceExhausted: CodeTooManyRequests, grpcCodes.Unauthenticated: CodeUnauthorized, grpcCodes.PermissionDenied: CodeForbidden, grpcCodes.NotFound: CodeNotFound, grpcCodes.AlreadyExists: CodeAlreadyExists, grpcCodes.Aborted: CodeConflict, grpcCodes.FailedPrecondition: CodeLocked, grpcCodes.DeadlineExceeded: CodeTimeout, grpcCodes.Internal: CodeInternal, grpcCodes.Unimplemented: CodeInternal, grpcCodes.Unavailable: CodeServiceUnavailable, grpcCodes.OK: CodeOK, } postgresCodesByCode = map[Code][]string{ CodeBadRequest: { pgerrcode.InvalidTextRepresentation, pgerrcode.InvalidParameterValue, }, CodeValidation: { pgerrcode.NotNullViolation, pgerrcode.CheckViolation, pgerrcode.StringDataRightTruncationDataException, pgerrcode.NumericValueOutOfRange, }, CodeNotFound: { pgerrcode.ForeignKeyViolation, }, CodeAlreadyExists: { pgerrcode.UniqueViolation, }, CodeConflict: { pgerrcode.ExclusionViolation, pgerrcode.SerializationFailure, pgerrcode.DeadlockDetected, }, CodeLocked: { pgerrcode.LockNotAvailable, pgerrcode.ObjectInUse, }, CodeTooManyRequests: { pgerrcode.TooManyConnections, }, CodeTimeout: { pgerrcode.QueryCanceled, }, CodeInternal: { pgerrcode.ConnectionException, pgerrcode.ConnectionFailure, pgerrcode.SQLClientUnableToEstablishSQLConnection, pgerrcode.SQLServerRejectedEstablishmentOfSQLConnection, pgerrcode.TransactionResolutionUnknown, }, CodeServiceUnavailable: { pgerrcode.CannotConnectNow, }, } codeByPostgresCode = buildCodeByPostgresCode(postgresCodesByCode) codeByPgxError = map[error]Code{ pgx.ErrNoRows: CodeNotFound, pgx.ErrTxClosed: CodeInternal, pgx.ErrTxCommitRollback: CodeConflict, pgx.ErrTooManyRows: CodeInternal, } ) func buildCodeByPostgresCode(src map[Code][]string) map[string]Code { dst := make(map[string]Code, len(src)) for code, pgCodes := range src { for _, pgCode := range pgCodes { dst[pgCode] = code } } return dst }