Skip to content

Instantly share code, notes, and snippets.

@will123195
Created June 30, 2022 19:06
Show Gist options
  • Save will123195/c240ca8d215b5318fd38c5e1efc0a1cb to your computer and use it in GitHub Desktop.
Save will123195/c240ca8d215b5318fd38c5e1efc0a1cb to your computer and use it in GitHub Desktop.
Express error handler for user-friendly postgres errors
import { errorHandler } from 'express-rest-error'; // need version 1.2.0+
// Make postgres errors more user-friendly
const pgErrorPatterns = [
{
regex: /null value in column "(.*)" violates not-null constraint/,
assign: (match) => ({
message: `${match[1]} is required`,
required: [match[1]],
}),
},
];
// error handler is last
app.use(
errorHandler({
debug: true,
transform: ({ err, req, res, responseBody }) => {
pgErrorPatterns.some((pattern) => {
const match = err.message.match(pattern.regex);
if (match) {
Object.assign(responseBody, pattern.assign(match));
err.httpStatus = 400;
//res.status(400);
}
return !!match;
});
return responseBody;
},
})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment