4 releases

0.2.0 Nov 24, 2024
0.1.2 Oct 26, 2024
0.1.1 Oct 26, 2024
0.1.0 Oct 26, 2024

#462 in Rust patterns

Download history 319/week @ 2024-10-25 21/week @ 2024-11-01 1/week @ 2024-11-08 4/week @ 2024-11-15 128/week @ 2024-11-22 22/week @ 2024-11-29 12/week @ 2024-12-06

166 downloads per month
Used in rp-supabase-client

MIT/Apache

33KB
650 lines

rp-postgrest-error

A Rust crate for parsing and handling error responses from PostgREST and PostgreSQL, providing structured error types and utility functions.

Features

  • Structured Error Types: Differentiate between PostgreSQL errors, PostgREST errors, and custom errors.
  • HTTP Status Mapping: Map error codes to corresponding HTTP status codes for API responses.
  • Detailed Error Information: Access error messages, details, and hints for better error handling.
  • Trait Implementations: Implements std::error::Error and Display traits for seamless integration with Rust’s error handling ecosystem.

Installation

Add the following to your Cargo.toml:

[dependencies]
rp-postgrest-error = "0.1.0"

Replace "0.1.0" with the latest version of the crate.

Usage

Parsing Error Responses

The crate provides an Error enum that represents different types of errors that can occur when interacting with PostgREST:

  • Error::PostgresError for PostgreSQL errors.
  • Error::PostgrestError for PostgREST-specific errors.
  • Error::CustomError for any other errors.

To parse an error response from PostgREST, you can use the from_error_response method:

use rp_postgrest_error::{Error, ErrorResponse};

// Example error response from PostgREST
let error_response = ErrorResponse {
    message: "duplicate key value violates unique constraint".to_owned(),
    code: "23505".to_owned(),
    details: Some("Key (id)=(1) already exists.".to_owned()),
    hint: None,
};

// Parse the error response
let error = Error::from_error_response(error_response);

match error {
    Error::PostgresError(pg_error) => {
        println!("PostgreSQL Error: {}", pg_error.message);
    }
    Error::PostgrestError(pgrst_error) => {
        println!("PostgREST Error: {}", pgrst_error.message);
    }
    Error::CustomError(custom_error) => {
        println!("Custom Error: {}", custom_error.message);
    }
}

Dependencies

~0.3–1MB
~21K SLoC