As alternative to looking at the http code, you could also look at the contents of a page. You would have to implement something where you actively check whether a new page has been opened, by checking for the presence of a specific element that is only shown on the expected page.
You could also define error pages, which have specific content such as text “Internal server error”.
If the check for the expected page fails, you can then first check whether you are on one of the error pages. If this is the case, throw a specific exception, otherwise just throw the original exception.
This is a very high level description of how it’s done in the framework Geb. More information here:
You might need to read a little bit more about the so called ‘At checking’ in the framework in addition to just the item that I linked to.