Improve error handling from piotrpasich's idea