How can I manage an exception generated by Postgis? I am running the following query on Postgres 10.3/Postgis 2.4:

create table table_c as (
    select A.*, B.area_name, B.id
    from table_a A
    left join table_b B
    on ST_Contains(A.geom, B.geom)
);


that fails with a cryptic:

ERROR:  GEOSContains: TopologyException: side location conflict at -2.0889721121124643 53.528652265475735


due to Postgis (and relative used libraries).

Is there a way to skip exceptional cases and keeping the query running until finished?
You can wrap the PostGIS function ST_Contains() in a plpgsql (or other PL) function of your own and trap the exception there. Like:

CREATE OR REPLACE FUNCTION f_ST_Contains(geometry, geometry)
  RETURNS boolean AS
$func$
BEGIN
   RETURN ST_Contains($1,$2);

EXCEPTION WHEN OTHERS THEN
   RETURN FALSE;  -- Return FALSE instead of raising an exception
END
$func$  LANGUAGE plpgsql IMMUTABLE;


This returns FALSE instead of raising an error. You might want return NULL instead. Same effect on your query.

And use that instead of ST_Contains() in your query:

...
ON f_ST_Contains(A.geom, B.geom)


Schema-qualify the function name in the function definition (and in the call) to remove dependency on the search path:

...
RETURN public.ST_Contains($1,$2);  -- actual schema of extension here
...


Not sure about implications on performance (especially index usage); didn't test.