Redirect in case of error

If there is a failure on the website server and we get an error response, for example 502, how to configure the automatic redirect to another URL in such cases?