error-response-plugin.js 1.1 KB

12345678910111213141516171819202122232425262728
  1. import { getStatusCode } from '../../status-code.js';
  2. import { sanitize } from '../../utils/sanitize.js';
  3. import { definePlugin } from '../define-plugin.js';
  4. function isResponseLike(obj) {
  5. return obj && typeof obj.writeHead === 'function';
  6. }
  7. function isSocketLike(obj) {
  8. return obj && typeof obj.write === 'function' && !('writeHead' in obj);
  9. }
  10. export const errorResponsePlugin = definePlugin((proxyServer, options) => {
  11. proxyServer.on('error', (err, req, res, target) => {
  12. // Re-throw error. Not recoverable since req & res are empty.
  13. if (!req || !res) {
  14. throw err; // "Error: Must provide a proper URL as target"
  15. }
  16. if (isResponseLike(res)) {
  17. if (!res.headersSent) {
  18. const statusCode = getStatusCode(err.code);
  19. res.writeHead(statusCode);
  20. }
  21. const host = req.headers && req.headers.host;
  22. res.end(`Error occurred while trying to proxy: ${sanitize(host)}${sanitize(req.url)}`);
  23. }
  24. else if (isSocketLike(res)) {
  25. res.destroy();
  26. }
  27. });
  28. });