scribase
SQLSTATE P0001raise_exceptionHTTP 400

Postgres error P0001: raise exception

raise_exception (a RAISE EXCEPTION in PL/pgSQL)

Your own function or trigger raised an error on purpose with RAISE EXCEPTION.

Common causes

  • A validation inside a trigger or function failed, and the message is whatever that code wrote.

How to fix it

  • Read the message and the function named in the CONTEXT line; fix the input or the rule.
  • Raise with your own SQLSTATE and HINT so clients can tell errors apart: raise exception 'Out of stock' using errcode = 'P0001', hint = 'Reduce the quantity';
sql
create function check_stock() returns trigger language plpgsql as $$
begin
  if new.qty > (select stock from products where id = new.product_id) then
    raise exception 'Not enough stock for product %', new.product_id
      using hint = 'Lower the quantity';
  end if;
  return new;
end $$;

Through a REST API

PostgREST, the REST layer behind supabase-js and Scribase, answers HTTP 400 for this error and returns the SQLSTATE in the code field of the JSON error body. PostgREST answers 400 and passes your message and hint to the client.

Questions

What does Postgres error P0001 mean?

P0001 is raise_exception in class P0 (PL/pgSQL Error). Your own function or trigger raised an error on purpose with RAISE EXCEPTION.

How do I fix P0001?

Read the message and the function named in the CONTEXT line; fix the input or the rule. Raise with your own SQLSTATE and HINT so clients can tell errors apart: raise exception 'Out of stock' using errcode = 'P0001', hint = 'Reduce the quantity';

What HTTP status does a REST API return for P0001?

PostgREST, the REST layer behind supabase-js, answers 400.