I'm working with Express Gateway to proxy requests to a backend service and want to transform error responses into a common format like this:
const errorResponse = {
timestamp: new Date().toISOString(),
status: status,
errorCode: errorCode,
message: message,
details: details
};
I tried using the built-in response-transformer policy in my gateway.config.yaml:
pipelines:
default:
apiEndpoints:
- companyApi
policies:
- log:
- action:
message: 'Request received: ${req.method} ${req.url}'
- proxy:
- action:
serviceEndpoint: backendService
changeOrigin: true
- response-transformer:
- action:
body:
# Tried adding transformations here but no effect
But the backend response is returned as-is; no transformation happens. Then I also tried creating a custom response-wrapper policy to intercept and change the response, but it seems that middleware is not applied or changing the response either.
response-wrapper policy
policy: () => {
return (req, res, next) => {
const originalSend = res.send.bind(res);
res.send = (body) => {
let backendMessage;
try {
backendMessage = typeof body === 'string' ? JSON.parse(body) : body;
} catch (e) {
backendMessage = body.toString();
}
const wrappedResponse = {
status: 'success',
message: backendMessage
};
res.set('Content-Type', 'application/json');
return originalSend(JSON.stringify(wrappedResponse));
};
next();
};
}
How can I properly intercept and transform error responses coming from a proxied backend in Express Gateway? Is response-transformer not suitable for this scenario or am I missing something in configuration?