session management factored out
Added error codes handling