I need to send custom error message in JSON format, from my express app, served in a lambda function using serverless-http
Please correct me if i got it wrong, but as i understand it, we need to use LAMBA_PROXY APIG integration to be able to send custom error messages defined directly from a lambda function.
This is what i have tried so far:
res.status(400).json({ message: 'email already taken' });
serverless.yml
functions:
auth:
handler: src/express/auth/index.handler
name: ${self:service}-auth-${env:STAGE}
# warmup: true
integration: lambda-proxy
memorySize: 128
timeout: 15
events:
- http:
path: /auth/
method: ANY
cors: true
- http:
path: /auth/{any+}
method: ANY
cors: true
this is what the API is returning(with status code 400)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Bad Request</pre>
</body>
</html>
Any leads, on how I can send a custom response, in JSON format?
update:
After more tests, I found out that calling next(error) doesn't reach the last error handler
const register = async (req, res, next) {
try {
await verifyEmail(req.body.email);
const user = await Users.register(req.body);
const token = sign(user.attrs, {});
res.json({ token, user });
} catch (e) {
next(e);
}
};
const generalError = async (err, req, res, next) => {
// doesn't reach this part! :(
console.log('generalError handler', JSON.stringify(err));
res.status(errorOut.status).json(errorOut);
};
ApiRouter.post('/register', register);
app.use('/auth', ApiRouter);
app.use(generalError);