Moved the error trap to the right location