Fix deadly bug and add errmsg