Best practices for handling planetscale DatabaseErrors with Drizzle?

How are you meant to catch certain/expected DB errors in your server code? This would be useful, for instance, to repeat insertion with a different ID if a user already exists.
import { DatabaseError } from '@planetscale/database';
// ...

try {
const isUserCreated = await this._userService.signUp(body);
return Respond.success(isUserCreated, { code: HTTPStatusCodes.Created201 });
} catch (e) {
if (e instanceof ApiError) {
return Respond.error(e.code, e.message, { details: e.details });
} else if (e instanceof DatabaseError) {
switch (e.status) { /* <- Is this the Mysql error code? */
case MySQLErrorCodes.ER_DUP_ENTRY:
// retry x times
break;
default:
return Respond.serverError('An error occured in the database', {
details: e.body
});
}
}
console.error(e);
return Respond.serverError('Unknown server error', e ? { details: e } : undefined);
}
import { DatabaseError } from '@planetscale/database';
// ...

try {
const isUserCreated = await this._userService.signUp(body);
return Respond.success(isUserCreated, { code: HTTPStatusCodes.Created201 });
} catch (e) {
if (e instanceof ApiError) {
return Respond.error(e.code, e.message, { details: e.details });
} else if (e instanceof DatabaseError) {
switch (e.status) { /* <- Is this the Mysql error code? */
case MySQLErrorCodes.ER_DUP_ENTRY:
// retry x times
break;
default:
return Respond.serverError('An error occured in the database', {
details: e.body
});
}
}
console.error(e);
return Respond.serverError('Unknown server error', e ? { details: e } : undefined);
}
Problem is, unlike Prisma, I don't seem to be able to access a mysql error code, all I get is an error message string like target: xyz.-.primary: vttablet: rpc error: code = AlreadyExists desc = Duplicate entry '1' for key 'user.user_username_unique' (errno 1062) (sqlstate 23000) .... Is my best bet really to parse the code using regex?
const errnoMatch = err.body.message.match(/errno (\d+)/);
if (errnoMatch) {
const errno = parseInt(errnoMatch[1]);
// Compare errno to MySQLErrorCodes enum
}
const errnoMatch = err.body.message.match(/errno (\d+)/);
if (errnoMatch) {
const errno = parseInt(errnoMatch[1]);
// Compare errno to MySQLErrorCodes enum
}
2 Replies
Liltripple_reid
Liltripple_reid10mo ago
upvoting this did you find a way to do this? @Domski
Domski
DomskiOP10mo ago
Unfortunately not, no
Want results from more Discord servers?
Add your server