SNI and advanced configuration of custom error pages

Is it possible to setup custom error pages in haproxy but only when the backend does not respond. ie when the backend is down haproxy sends out 503 error pages. We want our multidomain haproxy to send 503 error pages matching the domain requested.

We have tried setting up custom error pages like so:

http-errors domain1
    errorfile 503 /etc/haproxy/errors/503_domain1.http
http-errors domain2
    errorfile 503 /etc/haproxy/errors/503_domain.http

and in the frontend like so:

    http-response return status 503 errorfiles domain1 if { status 503 } { var(txn.host) www.domain1.com }
    http-response return status 503 errorfiles domain2 if { status 503 } { var(txn.host) domain2.com }

But that overrides all 503 error pages, also the ones sent from the backend and any custom headers set by the backend. We only want haproxy to send its own custom error pages if the backend does not respond. Is this possible?

I would declare errorfile(s) in each backend.

http-errors domain1
    errorfile 503 /etc/haproxy/errors/503_domain1.http
http-errors domain2
    errorfile 503 /etc/haproxy/errors/503_domain.http

backend domain1
    errorfiles domain1 503
    server server1 10.0.0.1:80

backend domain2
    errorfiles domain2 503
    server server2 10.0.0.2:80

# A way to declare an error file without having its own section.
backend domain3
    errorfile 503 /etc/haproxy/errors/503_domain3.http
    server server3 10.0.0.3:80

We only have one frontend section and one backend section. The requests are routed to the same set of servers altogether and responses are generated based on the domain requested. Is it strictly necessary to have a backend pr domain to be able to get the errorfile behavior we want?
We want to send the custom errorpages if and only if the backend does not respond. Should we in stead create a generic errorfile with some javascript that does some basic styling based on the domain requested?

The problem is that, as far as I can tell, errorfiles apply to a section of config, like default, frontend, and backend. I don’t see in any configuration documentation where errorfile(s) support if or unless statements. In order to make decisions, they have to be assigned to a unique section. You might try introducing some javascript as you say. Bear in mind that there is a limit on the size of an error file (noted here).