Created
June 30, 2022 19:06
-
-
Save will123195/c240ca8d215b5318fd38c5e1efc0a1cb to your computer and use it in GitHub Desktop.
Express error handler for user-friendly postgres errors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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