-
Does anyone have recommendations for type-narrowing the errors that postgres throws out, when using Typescript? Typescript's strict with errors, and treats them as unknown unless you can identify them as instances of a particular class or narrow the properties with a function. It doesn't look like there's an exported PostgresError class, so I can't use: if (err instanceof PostgresError) I've settled on a type-narrowing function that feels a bit like cheating: export function isPostgresError<T>(obj: T): obj is T & {
name: 'PostgresError';
code: string;
severity_local?: string;
severity?: string;
position?: string;
file?: string;
line?: string;
routine?: string;
detail?: string | undefined;
hint?: string | undefined;
internal_position?: string | undefined;
internal_query?: string | undefined;
where?: string | undefined;
schema_name?: string | undefined;
table_name?: string | undefined;
column_name?: string | undefined;
data?: string | undefined;
type_name?: string | undefined;
constraint_name?: string | undefined;
} {
return (
!!obj &&
(typeof obj == 'object' || typeof obj == 'function') &&
'name' in obj &&
obj.name === 'PostgresError' &&
'code' in obj &&
typeof obj.code === 'string'
);
} I can use this like so:
This is fine, I suppose, but I'm curious if there are any more elegant solutions. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Doh! I saw the solution in an open issue. import postgres from 'postgres';
try {
const result = await sql`select * from users`
} catch (err) {
if (err instanceof postgres.PostgresError) {
console.log(err.code) // This is now allowed!
} I got stumped because if you import the named PostgresError from the package, you wind up with a Typescript type that doesn't work for type narrowing. import { PostgresError } from 'postgres';
try {
const result = await sql`select * from users`
} catch (err) {
if (err instanceof PostgresError) { // This won't work! PostgresError is a Typescript type.
} |
Beta Was this translation helpful? Give feedback.
Doh! I saw the solution in an open issue.
I got stumped because if you import the named PostgresError from the package, you wind up with a Typescript type that doesn't work for type narrowing.