Handle exceptions thrown from middleware